竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生(=・ω・=)|

IIIID

园龄:4年5个月粉丝:3关注:23

【Java 8 新特性】Map转成List

一、使用Lambda表达式将Map转化成List

 

在Collectors.toList()方法中使用lambda表达式将Map转换为List,如下示例

1
List<String> valueList = map.values().stream().collect(Collectors.toList());

放入List之前对值进行排序:

1
List<String> sortedValueList = map.values().stream().sorted().collect(Collectors.toList());

使用给定的比较器(Comparator.comparing()):

1
2
3
4
List<BaselinePointVo> tmp = stringIntegerMap.entrySet().stream()
        .sorted(Comparator.comparing(e -> e.getKey()))
        .map(e ->new BaselinePointVo(e.getKey(), e.getValue()))
        .collect(Collectors.toList());

这里的 BaselinePointVo  是一个接收数据的类。使用Map.Entry获取Map的键和值如下:

1
2
3
4
List<BaselinePointVo> tmp = stringIntegerMap.entrySet().stream()
                    .sorted(Comparator.comparing(Map.Entry::getValue))
                    .map(e -> new BaselinePointVo(e.getKey(), e.getValue()))
                    .collect(Collectors.toList());

作为比较,也可以使用Map.Entry.comparingByValue()和Map.Entry.comparingByKey()分别根据值和键对数据进行排序:

1
2
3
4
List<BaselinePointVo> tmp = stringIntegerMap.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .map(e -> new BaselinePointVo(e.getKey(), e.getValue()))
                    .collect(Collectors.toList());

 


 

二、Map中的键或值转化成List示例

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
--Map中的值转换为List
List<String> valueList = map.values().stream().collect(Collectors.toList());
valueList.forEach(n -> System.out.println(n));
 
 
--Map中的值转换为List并排序
List<String> sortedValueList = map.values().stream()
.sorted().collect(Collectors.toList());
sortedValueList.forEach(n -> System.out.println(n));
 
 
--Map中的键转换为List
List<Integer> keyList = map.keySet().stream().collect(Collectors.toList());
keyList.forEach(n -> System.out.println(n));
 
 
--Map中的键转换为List并排序
List<Integer> sortedKeyList = map.keySet().stream()
.sorted().collect(Collectors.toList());
sortedKeyList.forEach(n -> System.out.println(n));

 

三、Map转化成List<T>示例

 

1
2
3
List<BaselinePointVo> list =stringIntegerMap.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey()))
        .map(e -> new BaselinePointVo(e.getKey(), e.getValue())).collect(Collectors.toList());
list.forEach(l -> System.out.println("Name "+ l.getName()+", Y: "+ l.getY()));

  

如果需要按键来排序的话,可以使用键来排序

1
Comparator.comparing(e -> e.getValue())

  

本文作者:IIIID

本文链接:https://www.cnblogs.com/Oxyy/p/15776067.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   IIIID  阅读(237)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起