kxz
kxz

Reputation: 63

How to sort a HashMap based on values in descending order?

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:

-or-

Upvotes: 1

Views: 3489

Answers (2)

prasad_
prasad_

Reputation: 14287

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}

Upvotes: 2

littleSaviour
littleSaviour

Reputation: 1

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));

Upvotes: 0

Related Questions