//将list转换成Map类型
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));
如果报 map里的value空指针异常,则需要在value,也就是toMap()的第二个参数进行空(null)值的判断逻辑;例如:也就是 Person::getName 改成 p -> p.getName()==null?"":p.getName()就可以解决value为null问题
<Person, String, String> Collector<Person, ?, Map<String, String>> java.util.stream.Collectors.toMap(Function<? super Person, ? extends String> keyMapper, Function<? super Person, ? extends String> valueMapper, BinaryOperator mergeFunction)
toMap()第三个参数是当有重复的Key时,会执行这段逻辑,传入2个参数,第一个参数是已经存在Map的value值,第二个是即将覆盖的value值,最终返回哪个值为准
本文介绍了如何使用Java Stream将List转换为Map,并处理可能出现的空值异常。通过在toMap方法中添加null值判断,避免了Person::getName返回null时引发的空指针异常。同时,解释了toMap的第三个参数作用,即当有重复Key时的处理逻辑。
5946

被折叠的 条评论
为什么被折叠?



