java利用stream流实现对hashmap的value值进行排序

我们都知道,hashmap本身是无序的,不可能做到排序,但是有时候又要排序该怎么办呢?

既然hashmap不行,那么有没有那种map集合是有序的呢?当然有,linkedhashmap就是其中的一种

所以解决问题的思路就是将hashmap转成linkedhashmap就好了

那么该如何转呢?这里推荐使用java8的stream流操作来转化

 

Map<String, Integer> unsortedMap= new HashMap<>();
unsortedMap.put("a",1);
unsortedMap.put("b",2);
unsortedMap.put("c",3);

LinkedHashMap<String, Long> sortedMap= new LinkedHashMap<>();
unsortedMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.forEachOrdered(s->sortedMap.put(s.getKey(),s.getValue()));

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
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来保留排序的顺序。 希望这个示例对你有所帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ivan_梦方舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值