I'm trying to keep my Java code conformant with null annotations, and I wanted to clarify whether my approach is correct for how to handle Map.getOrDefault() where I want the result to be annotated as @NotNull.
I want to get a non-null value from the map given a key, or an empty List object. The SDK specification for getOrDefault() indicates that it may return null. I want to resolve the null safety warning as simply as possible, without turning it off.
I came up with this solution, which has no dependencies and wraps around the method call nicely. Is this the simplest way to suppress this warning, as well as guarantee that I get a non-null result?
In this instance, I don't control the creation of the Map, so I can't guarantee whether a null key is valid or invalid. Therefore I have to account for both scenarios.
// Not annotated and may return null if key is null and there is no mapping for it (not what I want)
List<String> value = m.getOrDefault(key, new ArrayList<>());
// Null type mismatch; Map.getOrDefault() can be null!
@NotNull List<String> value = m.getOrDefault(key, new ArrayList<>());
// Guaranteed to return non-null result and handles null type safely
@NotNull List<String> value = Objects.requireNonNullElse(m.getOrDefault(key, null),new ArrayList<>());