stream將list轉化為map


在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流異常終止,使用時要格外注意這一點。

 

"管好自己,莫渡他人。"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM