java中Map按value排序

在刷题和业务编码的过程中有时会有对map按值进行排序的需求。总结了两种方法,它们都需要生成一个新的map作为返回:

方法一:借助List进行排序
	Map<String, Integer> map1 = new HashMap<>();
    map1.put("abc1", 5);
    map1.put("abc2", 3);
    map1.put("abc3", 20);
    map1.put("abc4", 80);
    map1.put("abc5", 1);
    map1.put("abc6", 10);
    map1.put("abc7", 12);
    List<Map.Entry<String,Integer>> list = new ArrayList<>(map1.entrySet()); //将Map转换成List
    Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue()); // 借助List的sort方法,需要重写排序规则
    // Collections.sort(list, Comparator.comparingInt(Map.Entry::getValue));  // IDE 提示可以写成更简便的这种形式,我还是习惯自己重新,然后lambda简化
    Map<String, Integer> map2 = new LinkedHashMap<>();  // 这里必须声明成为LinkedHashMap,否则构造新map时会打乱顺序
    for(Map.Entry<String, Integer> o:list){  // 构造新map
        map2.put(o.getKey(),o.getValue());
    }
    for(Map.Entry<String,Integer> entry:map2.entrySet()){  // out
        System.out.println(entry.getValue());
    }
方法二:借助stream进行排序
Map<String, Integer> sorted = map1
                .entrySet()
                .stream()
                .sorted(comparingByValue())
                .collect(
                        toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
                                LinkedHashMap::new));
// 这种方式在Leetcode上不能用,方法找不到
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值