Stream流 Collectors.toMap 根据收集自身对象

2022-08-04 09:17:43

Stream流 | Collectors.toMap 根据收集自身对象


日常开发中我们通常会想将List 集合根据某个成员变量为key 值将其转成Map 集合,如下:

GroupInfoEntity.java

@DatapublicclassGroupInfoEntity{/** 组织架构ID */privateLong id;/** 组织架构名称 */privateString name;/** 组织架构父ID */privateLong parentId;}

有一个封装上面实体的List 集合,现在有下面两个需求:
假设list 里面存了一些数据

List<GroupInfoEntity> list=newArrayList<>();
  • 1.根据idname 将其转成Map 集合
Map<Long,String> map= list.stream().collect(Collectors.toMap(GroupInfoEntity::getId,GroupInfoEntity::getName));
  • 2.根据id对象自己 转成 Map 集合
Map<Long,GroupInfoEntity> map= list.stream().collect(Collectors.toMap(GroupInfoEntity::getId,Function.identity()));

这样就很完美的得到自己想要的数据。


注意:

这里的Function.identity() 等价于t -> t,就是将对象自己返回。


  • 作者:慌途L
  • 原文链接:https://blog.csdn.net/qq_25112523/article/details/106944743
    更新时间:2022-08-04 09:17:43