JDK8 Lamdba表达式转换成Map,value为null问题

// 将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<String> mergeFunction) // toMap()第三个参数是当有重复的Key时,会执行这段逻辑,传入2个参数,第一个参数是已经存在Map的value值,第二个是即将覆盖的value值,最终返回哪个值为准
复制请注明出处,在世界中挣扎的灰太狼
原文地址:https://www.cnblogs.com/XingXiaoMeng/p/10939512.html