0

consider below code snippet:

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

it is throwing null pointer exception when null values goes in the map.

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)

I am not able to understand why is it so?

As far as i know it is fine to have null values in a HashMap?

slim
  • 40,215
  • 13
  • 94
  • 127
shanks
  • 117
  • 9

1 Answers1

0

The problem is not with HashMap but below code -

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

if s is null, it will throw an NPE. You need to do a null check there.

Anand Mattikopp
  • 332
  • 2
  • 11
  • Just use `"shashank".equalsIgnoreCase(s)` instead.I fail to see what this logic does though. you can just use `return 8` here as well since anything that matches your if clause has length 8. – Rob Obdeijn Nov 07 '17 at 14:10
  • Question isn't about s being null. It's about what `toMap()` does when `getLen()` returns null. – slim Nov 07 '17 at 14:13
  • Get it. As @slim updated above it's a known bug in JDK – Anand Mattikopp Nov 08 '17 at 15:59