我写了一个简单的片段
String aa = "aa";
String aaa = null;
String result = Optional.ofNullable(aa)
.map(s -> aaa)
.orElse("bb");
System.out.println(result);
orElse
应在aa
为空时执行。但是当 map
返回 null 时它也会被执行。
我的理解是只有aa
为null时才会执行orElse
。但是即使map返回null也会执行吗?
最佳答案
My understanding is that orElse will be executed only aa is null. But will it be executed even when map return null?
Optional.map
的实现可以更好地解释这一点。函数本身:
// return type function to map
public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper); // null check
if (!isPresent()) {
return empty(); // could be true when 'aa' is null in your case
} else {
return Optional.ofNullable(mapper.apply(value)); // using Optional.ofNullable itself
}
}
因此,如果应用 mapper
即在您的情况下 s -> aaa
返回 null
,则 map
操作将返回 Optional.empty
后跟 orElse
分支。
关于java - Optional Of Nullable 当 map 返回 null 时执行 orElse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53893496/