1

I'm trying to sort a HashMap based on values, so that its ordered in descending order. But I have no idea on how to implement it. How would I go about doing it?

HashMap<K, Integer> keysAndSizeMap = new HashMap<>();

for (K set : map.keySet()) {
     keysAndSizeMap.put(set, map.get(set).size());
}

// implementation here?

System.out.println("keysAndSizeMap: " + keysAndSizeMap);

Example of the result I want:

  • input: {800=12, 90=15, 754=20}
  • output: {754=20, 90=15, 800=12}

-or-

  • input: {"a"=2, "b"=6, "c"=4}
  • output: {"b"=6, "c"=4, "a"=2}
prasad_
  • 12,755
  • 2
  • 24
  • 36
kxz
  • 63
  • 1
  • 6

2 Answers2

2

This is one way of sorting a map by values using streams API. Note, the resulting map is a LinkedHashMap with descending order of its values.

Map<Integer, Integer> map = new HashMap<>();
map.put(1, 10);
map.put(12, 3);
map.put(2, 45);
map.put(6, 34);
System.out.println(map);

LinkedHashMap<Integer, Integer> map2 = 
    map.entrySet()
       .stream()             
       .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
       .collect(Collectors.toMap(e -> e.getKey(), 
                                 e -> e.getValue(), 
                                 (e1, e2) -> null, // or throw an exception
                                 () -> new LinkedHashMap<Integer, Integer>()));

System.out.println(map2);

Input: {1=10, 2=45, 6=34, 12=3}
Output: {2=45, 6=34, 1=10, 12=3}

prasad_
  • 12,755
  • 2
  • 24
  • 36
0

You can use TreeSet with custom comparators to sort the entries and Java 8 streams to create the sorted map.

TreeSet<Entry<T, Integer>> sortedEntrySet = new TreeSet<Entry<T, Integer>>((e1, e2) -> e2.getValue() - e1.getValue());
sortedEntrySet.addAll(keysAndSizeMap.entrySet());
Map<T, Integer> sortedMap = sortedEntrySet.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue));
entpnerd
  • 10,049
  • 8
  • 47
  • 68