【问题标题】:How to sort HashMap of String and Integer, by value and in case of duplicate then sort them by key, Including Russian words如何按值对字符串和整数的 HashMap 进行排序,如果重复,然后按键对它们进行排序,包括俄语单词
【发布时间】:2021-10-09 16:39:29
【问题描述】:

如何对 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));
}

【问题讨论】:

  • 但是当键相同时我无法对它们进行排序。但是如果您有HashMap,则键不能相同...
  • Map hm = new HashMap();我的意思是地图

标签: java sorting stream hashmap alphabetical


【解决方案1】:

我会这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2020-03-19
    • 2012-04-12
    相关资源
    最近更新 更多