java8,Stream排序Map集合

map根据key正序排序

map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey())).forEach(System.out::println);



map根据key倒序排序


map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).forEach(System.out::println);


map根据value正序排序

map.entrySet().stream().sorted(Comparator.comparing(e -> e.getValue())).forEach(System.out::println);


map根据value倒序排序

map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).forEach(System.out::println);

转载

https://blog.csdn.net/qq_50523945/article/details/134182735

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,使用Stream操作对Map进行排序是一种常见的需求。要对Map按照键或者值进行排序,你可以按照以下步骤进行操作: 1. 首先,将Map转换为一个包含Map.Entry对象的流,通过调用Map的entrySet()方法来实现。这样可以将Map中的键值对转换为一个流。 2. 接下来,使用sorted()方法对流进行排序。如果你想按照键进行排序,可以使用Comparator.comparingByKey()方法,并将其作为sorted()方法的参数。如果你想按照值进行排序,可以使用Comparator.comparingByValue()方法来实现。 3. 最后,使用collect()方法将排序后的流收集到一个新的Map中。可以使用Collectors.toMap()方法来实现这一步。 下面是一个示例代码,演示了如何使用Stream操作对Map进行排序: ``` // 假设我们有一个Map<String, Integer>的例子 Map<String, Integer> map = new HashMap<>(); map.put("apple", 3); map.put("banana", 2); map.put("orange", 4); // 按照键进行排序 Map<String, Integer> sortedByKey = map.entrySet() .stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); // 按照值进行排序 Map<String, Integer> sortedByValue = map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); // 输出排序后的结果 System.out.println("按照键排序后的Map:" + sortedByKey); System.out.println("按照值排序后的Map:" + sortedByValue); ``` 运行上述代码,你将会得到按照键和值排序后的Map。其中,sortedByKey将会得到按照键排序后的Map,sortedByValue将会得到按照值排序后的Map。注意,我们在使用Collectors.toMap()方法时指定了一个LinkedHashMap来保留排序的顺序。 希望这个示例对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值