[英]Facing NullPointerException while using Optional
I am using a Map<String, Optional<List<String>>>
. 我正在使用
Map<String, Optional<List<String>>>
。 I am getting an obvious NullPointerException
because the result is null
for that key. 我收到一个明显的
NullPointerException
因为该键的结果为null
。
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. 我试图通过使用Optional来避免
if-else
空检查。
You can use Map
's getOrDefault
method . 您可以使用
Map
的getOrDefault
方法 。
Returns the value to which the specified key is mapped, or
defaultValue
if this map contains no mapping for the key.返回指定键所映射到的值;如果此映射不包含键的映射关系,则返回
defaultValue
。
resultMap.put(MyEnum.ANIMAL,
map.getOrDefault(MyEnum.ANIMAL, Optional.of(new ArrayList<>())) );
This avoids the null
by having that method check for you. 这可以通过为您检查该方法来避免
null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.