加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 按整数值desc排序一个hashmap

发布时间:2020-12-14 05:59:13 所属栏目:Java 来源:网络整理
导读:如何按整数值对哈希映射进行排序,我找到的答案之一是 here 由Evgeniy Dorofeev撰写,他的回答是这样的 HashMapString,Integer map = new HashMapString,Integer(); map.put("a",4); map.put("c",6); map.put("b",2); Object[] a = map.entrySet().toArray();
如何按整数值对哈希映射进行排序,我找到的答案之一是 here

由Evgeniy Dorofeev撰写,他的回答是这样的

HashMap<String,Integer> map = new HashMap<String,Integer>();
    map.put("a",4);
    map.put("c",6);
    map.put("b",2);
    Object[] a = map.entrySet().toArray();
    Arrays.sort(a,new Comparator() {
        public int compare(Object o1,Object o2) {
            return ((Map.Entry<String,Integer>) o2).getValue().compareTo(
                    ((Map.Entry<String,Integer>) o1).getValue());
        }
    });
    for (Object e : a) {
        System.out.println(((Map.Entry<String,Integer>) e).getKey() + " : "
                + ((Map.Entry<String,Integer>) e).getValue());
    }

产量

c : 6
a : 4
b : 2

我的问题是如何成为描述?如果我想对HashMap Asc进行排序我该怎么做?

最后一个问题是:如何在排序后获得第一个元素?

解决方法

对于反向排序开关o2和o1.要获取第一个元素,只需访问索引0处的数组:
Map<String,Integer> map = new HashMap<>();
map.put("a",4);
map.put("c",6);
map.put("b",2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a,new Comparator() {
    public int compare(Object o1,Object o2) {
        return ((Map.Entry<String,Integer>) o1).getValue().compareTo(
               ((Map.Entry<String,Integer>) o2).getValue());
    }
});
for (Object e : a) {
    System.out.println(((Map.Entry<String,Integer>) e).getKey() + " : "
                     + ((Map.Entry<String,Integer>) e).getValue());
}        

System.out.println("first element is " + ((Map.Entry<String,Integer>) a[0]).getKey() + " : "
        + ((Map.Entry<String,Integer>) a[0]).getValue());

哪个打印

b : 2
a : 4
c : 6
first element is b : 2

如果您有权访问lambda表达式,则可以使用以下方法简化排序:

Arrays.sort(a,(o1,o2) -> 
   ((Map.Entry<String,Integer>) o1).getValue().compareTo(((Map.Entry<String,Integer>) o2).getValue()));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读