5

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for helping me out here.
I was also thinking of something like map.getOrDefault(MyEnum.ANIMAL, Optional.empty()).flatMap(this::doSomething).... It was kind of ambiguous to me what the OP actually wanted to do in case that the mapping was not present, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.