Java HashMap按值和键排序 [英] Java HashMap sort by value then key

查看:97
本文介绍了Java HashMap按值和键排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图首先按值(整数)然后按键(字符串)对HashMap进行排序。下面的方法似乎没有正确排序哈希映射。任何想法如何使它正常工作?

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

//按整数值排序,然后按字符串键
Collections.sort(list,(a,b) - > {
int cmp1 = a.getValue() .compareTo(b.getValue());
if(cmp1!= 0)
返回cmp1;
else
返回a.getKey()。compareTo(b.getKey( ));
});

地图< String,Integer> result = new HashMap<>(); (Map.Entry< String,Integer> entry:list)

result.put(entry.getKey(),entry.getValue());

返回结果;
}


解决方案

问题在于: / p>

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

使用 LinkedHashMap 添加键/值对的顺序。

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

解决方案

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.

这篇关于Java HashMap按值和键排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆