关于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