Lambda表达式 | 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
,就是将对象自己返回。