MathJax

Thursday, March 16, 2017

Java 8 Stream: stream().sorted.collect() throws NullPointerException

Here's what I ran into:

return map.keySet().stream()
    .sorted()
    .collect(Collectors.joining(":"));

was throwing NullPointerExceptions.

Why?

Turns out the original map actually had a value defined for the null key, as in
"a" -> "b"
null -> "c"

So the obvious first place to look is why on earth that silly null -> "c" mapping exists.

Another option, if this is safe for your use case, is to filter with java.util.Objects::nonNull:

return map.keySet().stream()
    .filter(Objects::nonNull)
    .sorted()
    .collect(Collectors.joining(":"));

No comments:

Post a Comment