Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facing NullPointerException while using Optional

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.

like image 783
RDM Avatar asked Mar 10 '18 00:03

RDM


People also ask

How do I use optional to avoid NULL pointer?

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 .

How do you handle optional null?

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.

Why is optional better for null handling?

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.

How do you know if an optional is null?

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.


1 Answers

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.

like image 118
rgettman Avatar answered Oct 01 '22 01:10

rgettman