Java——》Collectors.toMap的value为空时,报NullPointerException

推荐链接:
    总结——》【Java】
    总结——》【Mysql】
    总结——》【Spring】
    总结——》【SpringBoot】
    总结——》【MyBatis、MyBatis-Plus】

Java——》Collectors.toMap的value为空时,报NullPointerException

  • 1、操作
  • 2、现象(错误信息)
  • 3、原因
  • 4、解决

1、操作

Collectors.toMap(key,value)时,报NullPointerException异常

2、现象(错误信息)

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class T {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(null, 1, 2);

        // 当value为空时,报NullPointerException
        Map<Integer, Integer> map = list.stream().collect(Collectors.toMap(e -> e, e -> e));
        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.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
	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.eju.goodhouse.test.T.main(T.java:22)

3、原因

Collectors.toMap(),key可以为null,但 value不能为null, 否则抛空指针异常nullPointerException
Java——》Collectors.toMap的value为空时,报NullPointerException_第1张图片

4、解决

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class T {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(null, 1, 2);

        // 当value为空时,报NullPointerException
        // Map map = list.stream().collect(Collectors.toMap(e -> e, e -> e));
        // System.out.println(map);

        // 方案一:
        Map<Integer, Integer> map1 = list.stream().collect(HashMap::new, (hashMap, item) -> hashMap.put(item, item), (m1, m2) -> m1.putAll(m2));
        // 方案二:
        Map<Integer, Integer> map2 = list.stream().collect(HashMap::new, (hashMap, item) -> hashMap.put(item, item), HashMap::putAll);

        System.out.println(map1);
        System.out.println(map2);
    }
}

你可能感兴趣的:(Java,java,collectors,toMap,NullPointer)