1. 获取实体的某个属性组成Map
Map<Integer, String> map = list.stream().collect(Collectors.toMap(User::getId, User::getName));
2. 获取实体组成Map
Map<Integer, User> map= list.stream().collect(Collectors.toMap(User::getId, Function.identity()));
3. list转Map时报空指针
toMap 不允许value为null,所以在转map前需要将value为null的数据过滤掉。
或者赋值默认值
Map<Integer, String> map = list.stream().collect(Collectors.toMap(User::getId, s -> Optional.ofNullable(s.getName()).orElse("")));