Java8 Stream 操作 Collectors.toMap()会出现NullPointerException异常
List<People> peopleList = new ArrayList<>();
People people = new People();
people.setId(1L);
people.setUserName("sasa");
peopleList.add(people);
People people1 = new People();
people1.setId(2L);
peopleList.add(people1);
Map<Long, String> map = peopleList.stream().collect(Collectors.toMap(People::getId, People::getUserName));
System.out.println(map);
通过执行程序发现报错
Exception in thread "main" 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.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.example.demo.test.test.main(test.java:32)
Process finished with exit code 1
这是因为getUserName == null 引起的报错,为了解决这个坑,可以改为:
Map<Long, String> map2 = new HashMap<>();
for (People people2 : peopleList){
map2.put(people2.getId(), people2.getUserName());
}
或者
Map<Long, String> map1 = new HashMap<>();
peopleList.forEach(x->{
map1.put(x.getId(), x.getUserName());
});
或者
Map<Long, String> map3 = peopleList.stream().collect(Collectors.toMap(People::getId, x -> x.getUserName() == null ? "":x.getUserName()));