简体   繁体   中英

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:

  • 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}

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

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM