Facing NullPointerException when using optional

I am using Map<String, Optional<List<String>>> . I get an obvious NullPointerException because this key is null .

Is there a way to deal with a zero 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 if-else checking for null using an option.

+5
source share
1 answer

You can use the Map getOrDefault method .

Returns the value to which the specified key is mapped, or defaultValue if this map does not contain a mapping for the key.

 resultMap.put(MyEnum.ANIMAL, map.getOrDefault(MyEnum.ANIMAL, Optional.of(new ArrayList<>())) ); 

This avoids null by checking this method.

+5
source

Source: https://habr.com/ru/post/1275814/


All Articles