-2

I have this HashMap,

private static Map<String, Integer> messageCount = new HashMap<>();

which i'm trying to get sorted by the value. I found this code:

Map<String, Integer> sorted = Server.getMessageCount().entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                (e1, e2) -> e1, HashMap::new));

which theoretically should sort it by the Integer Value, but the Map is still getting sorted alphabetically (by key).

(I use this to output my map, but i'm pretty sure that this isn't the problem (or is it?))

System.out.println(Arrays.toString(sorted.entrySet().toArray()));
phil330d
  • 31
  • 1
  • 4
  • 4
    HashMap is not ordered. – SLaks May 13 '19 at 20:54
  • 1
    Check this link. https://stackoverflow.com/questions/8119366/sorting-hashmap-by-values – Sambit May 13 '19 at 20:54
  • 1
    What you're doing here is stream the map entries, sort them... and put them back into a new unsorted map. Use TreeMap or LinkedHashMap for a sortable map. – Joel May 13 '19 at 20:57

1 Answers1

3

As the docs says a HashMap does not keep the oder of the items.

... This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

You should use a LinkedHashMap instead. This keeps the insertion order (docs):

... This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Map<String, Integer> sorted = Server.getMessageCount()
         .entrySet().stream()
         .sorted(Map.Entry.comparingByValue())
         .collect(Collectors.toMap(
                 Map.Entry::getKey, Map.Entry::getValue,
                 (e1, e2) -> e1, LinkedHashMap::new
          ));
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
  • I guess he wants Map to be sorted by value. Should'nt he use `TreeMap` instead? – Razib May 13 '19 at 21:02
  • 1
    @Razib A `TreeMap` is sorted by key ("The map is sorted according to the natural ordering of its keys" - [docs](https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html)) – Samuel Philipp May 13 '19 at 21:05