如何对
HashMap
进行排序,首先按值排序,然后在值相同的情况下按字母顺序对它们进行排序,包括俄语单词。?
正确的输出应该如下所示(字符串是键,整数是值):
лицами-18
Apex-15
azet-15
xder-15
анатолю-15
андреевич-15
батальона-15
hello-13
zello-13
полноте-13
我只能按值对它们进行排序,但当键相同时我无法对它们进行排序。
以下代码对我有帮助,但它仅适用于单个字符:
private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap, final boolean order)
{
List<Entry<String, Integer>> list = new LinkedList<>(unsortMap.entrySet());
// Sorting the list based on values
list.sort((o1, o2) -> order ? 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));
}
private static void printMap(Map<String, Integer> map)
{
map.forEach((key, value) -> System.out.println("Key : " + key + " Value : " + value));
}
我会做这样的事情:
List<String> sortedEntries = unsortMap.entrySet().stream()
.sorted(Comparator.comparingLong(Map.Entry<String, Integer>::getValue)
.reversed()
.thenComparing(Map.Entry::getKey)
)
.map(it -> it.getKey() + "-" + it.getValue())
.collect(Collectors.toList());