Reputation: 63
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:
{800=12, 90=15, 754=20}
{754=20, 90=15, 800=12}
-or-
{"a"=2, "b"=6, "c"=4}
{"b"=6, "c"=4, "a"=2}
Upvotes: 1
Views: 3489
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
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