zoukankan      html  css  js  c++  java
  • stream将list转化为map

    在Stream流中将List转换为Map,是使用Collectors.toMap方法来进行转换。

    1.key和value都是对象中的某个属性值。

    Map<String, String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId, User::getName));

    2.key是对象中的某个属性值,value是对象本身(使用返回本身的lambda表达式)。

    Map<String, User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId, User -> User));

    3.key是对象中的某个属性值,value是对象本身(使用Function.identity()的简洁写法)。

    Map<String, User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

    4.key是对象中的某个属性值,value是对象本身,当key冲突时选择第二个key值覆盖第一个key值。

    Map<String, User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (oldValue, newValue) -> newValue));

    如果不正确指定Collectors.toMap方法的第三个参数(key冲突处理函数),那么在key重复的情况下该方法会报出【Duplicate Key】的错误导致Stream流异常终止,使用时要格外注意这一点。

    "管好自己,莫渡他人。"

    你要去做一个大人,不要回头,不要难过。
  • 相关阅读:
    #背包#nssl 1488 上升子序列
    #环#nssl 1487 图
    #分治#JZOJ 4211 送你一颗圣诞树
    #概率,dp#JZOJ 4212 我想大声告诉你
    #并查集#JZOJ 4223 旅游
    #dp#nssl 1478 题
    #对顶堆#nssl 1477 赛
    #线段树,离散#nssl 1476 联
    #折半搜索,状压dp#nssl 1471 Y
    #并查集,线性筛#nssl 1470 X
  • 原文地址:https://www.cnblogs.com/yanggb/p/14414611.html
Copyright © 2011-2022 走看看