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
,就是將對象自己返回。