• Stream ToMap(Collectors.toMap) 实践


    Requirements

    List TO Map
    List Stream 转换 Map时向collect()方法中传递Collector对象,对象由Collectors.toMap()方法返回。

    如下实现List转换为Map

    List list = new ArrayList<>(
          Arrays.asList(
                  new GroupBrandCateBO("v1", "g1", "b1"),
                  new GroupBrandCateBO("v1", "g1", "b1"),
                  new GroupBrandCateBO("v3", "g3", "b3")
          )
    );
    Map map = list.stream().collect(Collectors.toMap(item -> item.getVersion(), item -> item.getGroupCode(), (oldVal, currVal) -> oldVal, LinkedHashMap::new)); 
    System.out.println(map.getClass());
    Map map0 = list.stream().collect(Collectors.toMap(item -> item.getVersion(), item -> item.getGroupCode(), (oldVal, currVal) -> oldVal));
    System.out.println(map0.getClass());
    System.out.println(map0.toString());
    Map map1 = list.stream().collect(Collectors.toMap(GroupBrandCateBO::getVersion, GroupBrandCateBO::getGroupCode));
    System.out.println(map1.toString());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    Console
    class java.util.LinkedHashMap
    class java.util.HashMap
    {v1=g1, v3=g3}
    Exception in thread “main” java.lang.IllegalStateException: Duplicate key g1
    at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)

    问题分析

    toMap()函数重载:
    未指定合并函数mergeFunction情况下,传入throwingMerger()返回BinaryOperator对象,当出现key重复时,调用合并函数!
    未指定Supplier实例情况下,默认生成HashMap实例。

    public static 
    Collector> toMap(Function keyMapper,
                                    Function valueMapper) {
        return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
    }
    
    public static 
    Collector> toMap(Function keyMapper,
                                    Function valueMapper,
                                    BinaryOperator mergeFunction) {
        return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
    }
    
    public static >
    Collector toMap(Function keyMapper,
                                Function valueMapper,
                                BinaryOperator mergeFunction,
                                Supplier mapSupplier) {
        BiConsumer accumulator
                = (map, element) -> map.merge(keyMapper.apply(element),
                                              valueMapper.apply(element), mergeFunction);
        return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
    }
    
    private static  BinaryOperator throwingMerger() {
        return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    补充

    关于合并函数

    List list = new ArrayList<>(
           Arrays.asList(
                   new GroupBrandCateBO("v1", "g1", "b1"),
                   new GroupBrandCateBO("v1", "g2", "b2"),
                   new GroupBrandCateBO("v1", "g2", "b2"),
                   new GroupBrandCateBO("v3", "g3", "b3")
           )
    );
    Map map00 = list.stream().collect(Collectors.toMap(item -> item.getVersion(), item -> item.getGroupCode(), (oldVal, currVal) -> currVal));
    Map map01 = list.stream().collect(Collectors.toMap(item -> item.getVersion(), item -> item.getGroupCode(), (oldVal, currVal) -> oldVal + currVal));
    System.out.println(map00.toString());
    System.out.println(map01.toString());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    Console
    {v1=g2, v3=g3}
    {v1=g1g2g2, v3=g3}

    传入Lambda表达式将转化为BinaryOperator mergeFunction对象,合并处理value,非Key!!!
    比如:

    (oldVal, currVal) -> currVal) // key相同时当前值替换原始值
    (oldVal, currVal) -> oldVal + currVal //key相同时保留原始值和当前值
    
    • 1
    • 2
  • 相关阅读:
    30天Python入门(第二十四天:深入了解Python中的Numpy)
    MES生产管理系统的五个关键组件
    如何基于TS在React中使用Redux Toolkit
    java.sql.SQLException: Unknown system variable ‘query_cache_size‘ 报错处理
    网站如何部署到阿里云服务器教程
    智慧实验室系统云LIS全套源码,满足医院实验室、医院集团、独立实验室、临检中心及其它检验机构的专业化检验需求。
    高效备考2025年AMC8数学竞赛:2000-2024年AMC8真题练一练
    android service基本介绍
    【Vue】事件处理
    看看GPT-4V是怎么开车的,必须围观,大模型真的大有作为 | 万字长文
  • 原文地址:https://blog.csdn.net/nana1253431195/article/details/126516661