I want to filter some values in the Map
via Stream
. Let's see the simple example, where I want to extract entries with keys, for example, higher than 2.
Here is the code I use:
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
Map<Integer, String> map2 = map.entrySet().stream()
.filter(e -> e.getKey() > 2)
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
System.out.println(map2.toString());
The result correct:
{3=three, 4=four}
When I decide to put the String value as null
, that's legal, this is thrown:
Exception in thread "main" java.lang.NullPointerException
Here is the continuation of the code:
map.put(5, null);
map.put(6, "six");
Map<Integer, String> map3 = map.entrySet().stream()
.filter(e -> e.getKey() > 2)
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
System.out.println(map3.toString());
I would expect the result:
{3=three, 4=four, 5=null, 6=six}
Well, it works when I change the condition in the filter's Predicate
to e -> e.getKey() < 2
since the null
value is unaffected. How to handle this with Stream
? The null
value may occur anywhere intentionally. I don't want to use the for-loop. Shouldn't Stream
architecture be more "null-safe"?
The question How should we manage jdk8 stream for null values deals with the different problem. I don't want to use .filter(Objects::nonNull)
because I need to keep the null
values.
Please don't mark it as duplicate with famous What is a NullPointerException and how do I fix it. I know this well, I ask the solution using Stream
, that is not as low-level as for-loop is. This behaviour quite limits me.