文
章
目
录
章
目
录
最近线上Java程序运行有个报错error,具体类似如下NullPointerException空指针异常,主要发生在Stream流中的调用Collectors.toMap方法中,提示HashMap.merge时出现空指针异常:
java.lang.NullPointerException
at java.util.HashMap.merge(HashMap.java:1225)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.sf.hlcs.sda.Test01.test1(Test01.java:28)
这里是模拟的演示代码:
@Test
public void test1() {
Person person = new Person();
person.setAge(null);
person.setName("panziye");
List<Person> personList = new ArrayList<>();
personList.add(person);
personList.stream().collect(Collectors.toMap(Person::getName, Person::getAge));
}
@Data
class Person{
private String name;
private String age;
}
Collectors.toMap HashMap.merge空指针异常原因
原因其实很简单,就是因为Collectors.toMap是对应的value值为null导致的。我们直接看下Collectors.toMap相关源码:
我们发现Collectors.toMap中会调用merge方法,当value为null时就直接抛空指针异常了。
解决办法
我们使用filter过滤null值后再去collect,比如以上的代码优化如下:
personList.stream().filter(e -> e.getAge() != null).collect(Collectors.toMap(Person::getName, Person::getAge));
这样就轻松解决了HashMap.merge空指针异常问题,但是如果你想保留为null的值,那就可以使用Optional:
// 使用 Optional 来获取值,若为null,则返回默认值""
personList.stream().collect(Collectors.toMap(Person::getName, p->Optional.ofNullable(p.getAge()).orElse("")));
当然还有一种办法,就是直接调用map中的put()方法,而不使用toMap()中默认的merge()方法,我们可以不使用toMap()方法,直接在collect中构建map,类似如下:
personList.stream().collect(
HashMap::new,
(m,node) -> m.put(node.getName(),node.getAge()),
HashMap::putAll
);
以上就是Stream Collectors.toMap抛HashMap.merge空指针异常的原因分析及相关解决办法,希望对你有帮助!