【问题标题】:Java HashMap sort by value then keyJava HashMap 按值然后键排序
【发布时间】:2015-11-26 19:30:17
【问题描述】:

我试图先按值(整数)然后按键(字符串)对 HashMap 进行排序。以下方法似乎无法正确排序哈希图。任何想法如何使其正常工作?

private static Map<String, Integer> sortHash(Map<String, Integer> map) {
    List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());

    // Sort list by integer values then by string keys
    Collections.sort(list, (a, b) -> {
        int cmp1 = a.getValue().compareTo(b.getValue());
        if (cmp1 != 0)
            return cmp1;
        else
            return a.getKey().compareTo(b.getKey());
    });

    Map<String, Integer> result = new HashMap<>();
    for (Map.Entry<String, Integer> entry : list)
        result.put(entry.getKey(), entry.getValue());

    return result;
}

【问题讨论】:

  • 比较器的更好实现是list.sort(Map.Entry.comparingByValue().thenComparing(Map.Entry.comparingByKey()))
  • @LouisWasserman 初始化列表后是否必须调用它? This 就是我所看到的。不确定我到底错过了什么。
  • 如果您只是将结果放入没有保证顺序的 HashMap 中,您会不会遇到问题?我认为您需要查看 TreeMap 并为其提供比较器。见link

标签: java sorting hashmap


【解决方案1】:

问题就在这里:

Map<String, Integer> result = new HashMap<>();

使用LinkedHashMap,因为此映射将保持键/值对的添加顺序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-23
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2014-01-18
    • 1970-01-01
    • 2017-09-22
    相关资源
    最近更新 更多