Java HashMap sort by value then key

那年仲夏 提交于 2019-12-24 15:27:28

问题


I am trying to sort a HashMap first by value (integer) then by key (string). The following method doesn't appear to be sorting the hashmap properly. Any ideas how to make it work properly ?

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

回答1:


The issue is here:

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

Use LinkedHashMap since this map will maintain the order of the addition of the key/value pairs.



来源:https://stackoverflow.com/questions/33945836/java-hashmap-sort-by-value-then-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!