I am using a Map<String, Optional<List<String>>>
. I am getting an obvious NullPointerException
because the result is null
for that key.
Is there any way to handle the null situation?
public Map<MyEnum, Optional<List<String>>> process(Map<MyEnum, Optional<List<String>>> map) {
Map<MyEnum, Optional<List<String>>> resultMap = new HashMap<>();
// Getting NullPointerException here, since map.get(MyEnum.ANIMAL) is NULL
resultMap.put(MyEnum.ANIMAL, doSomething(map.get(MyEnum.ANIMAL).get()));
// do something more here
}
private Optional<List<String>> doSomething(List<String> list) {
// process and return a list of String
return Optional.of(resultList);
}
I am trying to avoid a if-else
check for null by using Optional.
An empty optional is the main way to avoid the Null Pointer Exception when using the Optional API. In Optional 's flow, a null will be transformed into an empty Optional . The empty Optional won't be processed any further. This is how we can avoid a NullPointerException when using Optional .
Optional from nullable value: You can create an optional object from a nullable value using the static factoy method Optional. ofNullable . The advantage over using this method is if the given value is null then it returns an empty optional and rest of the operations performed on it will be supressed.
In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.
Optional is a container object that can contain a non-null or null value. It basically checks whether the memory address has an object or not. If a value is present, isPresent() will return true and get() will return the value.
You can use Map
's getOrDefault
method.
Returns the value to which the specified key is mapped, or
defaultValue
if this map contains no mapping for the key.
resultMap.put(MyEnum.ANIMAL,
map.getOrDefault(MyEnum.ANIMAL, Optional.of(new ArrayList<>())) );
This avoids the null
by having that method check for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With