目 录CONTENT

文章目录

List转map的写法

在水一方
2022-09-07 / 0 评论 / 0 点赞 / 685 阅读 / 1,703 字 / 正在检测是否收录...

实际业务中经常会有需要将List转为Map的需求,由于对于这部分的编写情况不太熟悉,于是先写几个测试demo看看具体的编写方法

开发手册规范

规范1
【强制】在使用 java.util.stream.Collectors 类的 toMap()方法转为 Map 集合时,一定要使用含有参数类型为 BinaryOperator,参数名为 mergeFunction 的方法,否则当出现相同 key值时会抛出IllegalStateException 异常。
说明:参数 mergeFunction 的作用是当出现 key 重复时,自定义对 value 的处理策略。
正例:

List<Pair<String, Double>> pairArrayList = new ArrayList<>(3);
pairArrayList.add(new Pair<>("version", 12.10));
pairArrayList.add(new Pair<>("version", 12.19));
pairArrayList.add(new Pair<>("version", 6.28));
Map<String, Double> map = pairArrayList.stream().collect(
// 生成的 map 集合中只有一个键值对:{version=6.28}
Collectors.toMap(Pair::getKey, Pair::getValue, (v1, v2) -> v2));

规范2
【强制】在使用 java.util.stream.Collectors 类的 toMap()方法转为 Map 集合时,一定要注意当 value 为 null 时会抛 NPE 异常。

List转Map的demo1:
返回的map类型:Map<String,String>

   @Test
    public void toMap(){
        List<Content> list = List.of(new Content("name", "xiaoming"), new Content("age", "18"));
        Map<String,String> map = list.stream().collect(Collectors.toMap(Content::getName, Content::getAge, (k1, k2) -> k2));
        map.forEach((x,y)->{
            System.out.println(x);
            System.out.println(y);
        });
    }

List转Map的demo2:

返回的类型Map<String,Content>


    @Test
    public void toMap(){
        List<Content> list = List.of(new Content("name", "xiaoming"), new Content("age", "18"));
        Map<String,Content> map = list.stream().collect(Collectors.toMap(Content::getName, Function.identity(), (k1, k2) -> k2));
        map.forEach((x,y)->{
            System.out.println(x);
            System.out.println(y);
        });
    }

说明:Function.identity()返回一个输出跟输入一样的Lambda表达式对象

dmeo3:通过分组的方式来得到Map

Map<String, List<Content>> groupBy = list.stream().collect(Collectors.groupingBy(Content::getName));
0

评论区