Stream流 | Collectors.toMap 根据收集自身对象
日常开发中我们通常会想将 List 集合根据某个成员变量为 key 值将其转成 Map 集合,如下:
GroupInfoEntity.java
@Data
public class GroupInfoEntity{
/** 组织架构ID */
private Long id;
/** 组织架构名称 */
private String name;
/** 组织架构父ID */
private Long parentId;
}
有一个封装上面实体的 List 集合,现在有下面两个需求:
假设 list 里面存了一些数据
List<GroupInfoEntity> list = new ArrayList<>();
-
1.根据
id和name将其转成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,就是将对象自己返回。
本文介绍了如何使用Java 8的Stream流结合Collectors.toMap方法,将List集合高效地转换为Map。示例中展示了如何根据GroupInfoEntity的id和name创建Map,以及如何以id为key保持对象本身。Function.identity()函数在此过程中用于保持对象不变。
6111

被折叠的 条评论
为什么被折叠?



