当前位置: 首页 > article >正文

Collectors.toMap

Java8 中新增了 Stream 特性,使得我们在处理集合操作时更方便。

实例

以下例子可以参考 :

  • https://juejin.cn/post/6981651287976722445
List<User> userList = Lists.newArrayList(
        new User().setId("A").setName("张三"),
        new User().setId("A").setName("李四"), // Key 相同 
        new User().setId("C").setName("王五")
);
userList.stream().collect(Collectors.toMap(User::getId, User::getName));

// 异常:
java.lang.IllegalStateException: Duplicate key 张三 
    at java.util.stream.Collectors.lambda$throwingMerger$114(Collectors.java:133)
    at java.util.HashMap.merge(HashMap.java:1245)
    at java.util.stream.Collectors.lambda$toMap$172(Collectors.java:1320)
    at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at Test.toMap(Test.java:17)
    ...

调用第二个重载方法,传入合并函数

userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n1 + n2));

// 输出结果:
A-> 张三李四 
C-> 王五
其他实例
return executorSummaryList.stream()
      .collect(Collectors.toMap(v -> v.id,
        v -> {
          List<ExecutorSummary> summaryList = new ArrayList<>();
          summaryList.add(v);
          return summaryList;
        },
        (v1, v2) -> {
          v1.addAll(v2);
          return v1;
        }));
    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the specified
     * collection's iterator (optional operation).  The behavior of this
     * operation is undefined if the specified collection is modified while
     * the operation is in progress.  (Note that this will occur if the
     * specified collection is this list, and it's nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of an element of the specified
     *         collection prevents it from being added to this list
     * @throws NullPointerException if the specified collection contains one
     *         or more null elements and this list does not permit null
     *         elements, or if the specified collection is null
     * @throws IllegalArgumentException if some property of an element of the
     *         specified collection prevents it from being added to this list
     * @see #add(Object)
     */
    boolean addAll(Collection<? extends E> c);

http://www.kler.cn/news/233596.html

相关文章:

  • MySQL基础查询篇(9)-数学函数在查询中的应用
  • Linux中的numactl命令指南
  • 代码随想录算法训练营day15||二叉树part02、102.二叉树的层序遍历、 226.翻转二叉树(优先掌握递归)、101. 对称二叉树 (优先掌握递归)
  • MATLAB实现随机森林回归算法
  • 会声会影绿幕抠图操作方法 会声会影绿幕抠图有绿色残边 绿幕抠图视频有绿边怎么处理 抖音怎么剪辑视频 视频剪辑软件推荐
  • Linux 设置自动挂载磁盘
  • LabVIEW伺服阀性能参数测试
  • VitePress-13- 配置-title的作用详解
  • 微服务介绍、使用 Nacos 实现远程调用以及 OpenFeign 的使用
  • containerd中文翻译系列(二十)快照器
  • OnlyOffice-8.0版本深度测评
  • 鸿蒙开发系列教程(十四)--组件导航:Tabs 导航
  • codeforces 126B password
  • CSS中的继承是什么?哪些属性可以继承,哪些不能继承?
  • Blazor入门100天 : 自做一个手势滑动组件
  • 计算机视觉 | OpenCV 实现手势虚拟控制亮度和音量
  • 【Python 千题 —— 基础篇】查找年龄
  • C++ static 修饰全局变量时的作用探究
  • ARM PAC/BTI/MTE三剑客精讲与实战
  • 【2024-01-20】 瑞幸咖啡小程序-blackbox
  • 视觉开发板—K210自学笔记(二)
  • centos中docker操作
  • Android性能调优 - 应用安全问题
  • Redis(三)主从架构、Redis哨兵架构、Redis集群方案对比、Redis高可用集群搭建、Redis高可用集群之水平扩展
  • 018 Linux
  • SQL 使用大全
  • 【Linux笔记】动静态库的封装和加载
  • C++ 中->成员访问运算符
  • 有道论文翻译接口,python版和lua版
  • ubuntu22.04@laptop OpenCV Get Started: 003_image_resizing