在Stream流中將List轉換為Map,是使用Collectors.toMap方法來進行轉換。
1.key和value都是對象中的某個屬性值。
Map<String, String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId, User::getName));
2.key是對象中的某個屬性值,value是對象本身(使用返回本身的lambda表達式)。
Map<String, User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId, User -> User));
3.key是對象中的某個屬性值,value是對象本身(使用Function.identity()的簡潔寫法)。
Map<String, User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
4.key是對象中的某個屬性值,value是對象本身,當key沖突時選擇第二個key值覆蓋第一個key值。
Map<String, User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (oldValue, newValue) -> newValue));
如果不正確指定Collectors.toMap方法的第三個參數(key沖突處理函數),那么在key重復的情況下該方法會報出【Duplicate Key】的錯誤導致Stream流異常終止,使用時要格外注意這一點。
"管好自己,莫渡他人。"