如何按降序打印 HashMap 值,但如果两个或多个值相等,请按键升序打印它们?(爪哇)



例如我们有

Map<String, Integer> map = new HashMap<>();
map.put("fragments", 5);
map.put("motes", 3);
map.put("shards", 5);

我想像这样打印它们:

fragments: 5
shards: 5
motes: 3

我会通过首先将值放在TreeMap中来解决这个问题

然后我会根据相等的值对键进行排序,并将它们放在一个LinkedHashMap以维护订单。

Map<String, Integer> map = new TreeMap<>();
map.put("motes", 3);
map.put("shards", 5);
map.put("fragments", 5); 
map = map.entrySet().stream().sorted(Comparator.comparing(
Entry<String, Integer>::getValue).reversed()).collect(
LinkedHashMap<String, Integer>::new,
(map1, e) -> map1.put(e.getKey(), e.getValue()),
LinkedHashMap::putAll);
map.entrySet().forEach(System.out::println);

基于此处的出色答案,请考虑以下解决方案:

public static void main(String[] args) {
final Map<String, Integer> originalMap = new HashMap<>();
originalMap.put("fragments", 5);
originalMap.put("motes", 3);
originalMap.put("shards", 5);
final Map<String, Integer> sortedMap = sortByValue(originalMap, false);
sortedMap
.entrySet()
.stream()
.forEach((entry) -> System.out.println(entry.getKey() + " : " + entry.getValue()));
}
private static Map<String, Integer> sortByValue(Map<String, Integer> unsortedMap, final boolean ascending) {
List<Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());
// Sorting the list based on values
list.sort((o1, o2) -> ascending ? o1.getValue().compareTo(o2.getValue()) == 0
? o1.getKey().compareTo(o2.getKey())
: o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0
? o2.getKey().compareTo(o1.getKey())
: o2.getValue().compareTo(o1.getValue()));
return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new));
}