前言
略
Collectors.toMap
List<User> userList = ...;
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));
假如id存在重复值,则会报错Duplicate key xxx, 解决方案
两个重复id中,取后一个:
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity(),(oldValue,newValue) -> newValue));
两个重复id中,取前一个:
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity(),(oldValue,newValue) -> oldValue));
转 id 和 name
Map<Long, String> map = userList.stream().collect(Collectors.toMap(User::getUserId, User::getName));
name 为 null 的解决方案:
Map<Long, String> map = userList.stream().collect(Collectors.toMap(Student::getUserId, e->e.getName()==null?"":e.getName()));