java8Collectors.toMap 的value为null的时候报NullPointException ,key重复报IllegalStateException: Duplicate key

使用jdk8对于熟悉的的还好,要是不熟悉,肯定会有很多坑

有时候我们查询数据库得到一个List集合,然后将list集合使用Stream流将List集合映射成map,如下面的形式:

  ArrayList<Person> persons= new ArrayList<>();
        Person person1 = new Person();
        person1.setName("fsf");
        person1.setCareer("");
        Person person2 = new Person();
        person2.setName("dfs");
        person2.setCareer(null);
 
Map<String, String> collect = persons.stream().collect(Collectors.toMap(Person::getName,Person::getCareer));

假设上面的persons是我们数据库查询的结果,数据库默认字段为null,并且可以为空,查出来会出现何lsit集合类似的结果。

这个时候测试一下运行一下,发现

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 bettercode.TestMap.main(TestMap.java:26)

这是因为map的value值为空导致,简单的更改如下

 Map<String, String> collect = persons.stream().collect(HashMap::new,(k, v) ->k.put(v.getName(),v.getCareer()),HashMap::putAll);

这样可以避免空指针的问题,这种写法对于重复的key也会进行处理,当map有重复的key时,后面的key值会把前面的key值覆盖掉,理论上我们的key都是唯一的,也不会出现重复的key。

还有一种简单的写法,就是最传统的方式

     Map<String,String>  map=new HashMap<>();
        persons.forEach(e->{
            map.put(e.getName(),e.getCareer());
        });

猜你喜欢

转载自blog.csdn.net/qq_35410620/article/details/90373451