關於stream Collectors.toMap的使用


轉map時自定義key

userDOS.stream().collect(Collectors.toMap(k -> k.getUserId() + "c", Function.identity()));

當key重復時,會報IllegalStateException異常
解決辦法

新的值覆蓋老的值
userDOS.stream().collect(Collectors.toMap(k -> k.getUserId() + "c",Function.identity(), (oldValue, newValue) -> newValue));

value為null時會拋出空指針異常

會vale進行判空
userDOS.stream().collect(Collectors.toMap(k -> k.getUserId() + "c",UserDO-> UserDO.getUserId()==null?1l: UserDO.getUserId(), (oldValue, newValue) -> newValue));

userDOS.stream().collect(HashMap::new,(n, v) -> n.put(v.getUserId(), v.getUsername()), HashMap::putAll);


免責聲明!

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



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