前言
略
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()));