There is a HashMap<String, Integer> , is it possible to make a primary sorting by type String?

  • Use TreeMap instead of HashMap ? - diraria
  • one
    If you want sorting, then use TreeMap, if you want sorting as you write to the map, then use LinkedHashMap - Miguel Bravo
  • Thanks, LinkedHashMap helped. With TreeMap I tried, there are some minor problems - it besides the first parameter also sorts the second one - Egor Nikulin

1 answer 1

Option with LinkedHashMap

  Map<String, Integer> result = unsortMap.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));