【Java 8 新特性】Map转成List

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

 

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

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

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

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

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

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的键和值如下:

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()分别根据值和键对数据进行排序:

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

 


 

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

 

--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>示例

 

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()));

  

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

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

  

posted @ 2022-01-07 17:31  IIIID  阅读(148)  评论(0编辑  收藏  举报