3

I have a Map (a multi-map, of sorts) with the following signature:

Map<String, Set<String>> motherChildIndex;

If the key doesn't exist in the map, I would prefer that it return an empty set (as opposed to null), so I stumbled upon the getOrDefault method, which should allow me to "ignore" nulls, effectively.

Here is my relevant code:

motherChildIndex
        .getOrDefault(personId, Collections.emptySet()) //personId is just a string that may or may not be in the map, hence getOrDefault
        .stream() //I get the warning here
        .map(personsIndex::get) //Not important to reproduce
        .forEach(children::add); //Not important to reproduce

On the .stream() line, I get a warning:

Method invocation 'stream' may produce 'java.lang.NullPointerException'

Why? I thought getOrDefault() was supposed to never return a null.

I'm using Android Studio as my IDE, if that makes any difference.

Cache Staheli
  • 3,510
  • 7
  • 32
  • 51

1 Answers1

0

Looks like getOrDefault() has RecentlyNullable annotation in Map.class, which looks like the Nullable annotation (and this is entirely my interperation, only question on the matter is this if you want to read: what is the @RecentlyNonNull annotation?).

Hence, I assume IntelliJ reads it and immediately warns you about it's possibility to return a null value, therefore thinks the stream() might throw a NullPointerException (since to IntelliJ the map can be null), then suggests you to have a nonNull check on the map.

Weird thing is that (as in the stackoverflow question as well) the annotation is not in the Java docs apparently.

coras09
  • 333
  • 3
  • 11