Java lambda toMap

时间:2017-11-07 14:01:33

标签: java lambda

请考虑以下代码段:

   Stream.of("a", "b").collect(Collectors.toMap( 
              s -> s, 
              s -> "a".equals(s) ? "a" : null));
    }

当空值出现在地图中时,它会抛出空指针异常。

java.lang.NullPointerException
at java.util.HashMap.merge(HashMap.java:1224)
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)

我无法理解为什么会这样?

据我所知,在HashMap中有空值可以吗?

1 个答案:

答案 0 :(得分:0)

问题不在于HashMap,而在于代码 -

if (s.equalsIgnoreCase("shashank")) {
        return s.length();
    }

如果s为null,则会抛出NPE。你需要在那里进行空检查。