Bha*_*gat 2 java optional java-8
下面的代码打印:
should Not have called
hello world
Run Code Online (Sandbox Code Playgroud)
为什么orElse即使有包含值的Optional也要执行?
public static void main(String[] args){
String o = Optional.ofNullable("world").map(str -> "hello" + str).orElse(dontCallMe());
System.out.println(o);
}
private static String dontCallMe() {
System.out.println("should Not have called");
return "why god why";
}
Run Code Online (Sandbox Code Playgroud)
该orElse方法如下所示:
public T orElse(T other) {
return value != null ? value : other;
}
Run Code Online (Sandbox Code Playgroud)
这里没有任何复杂的逻辑。
与任何方法一样,它将执行以下操作:
我们实际上并不在乎参数的值这一事实并不会改变此过程(这只是语言设计的好坏)。
如果您不希望在参数中调用方法,则可能是在寻找Optional.orElseGet。
这个:
public static void main(String[] args){
String o = Optional.ofNullable("world").map(str -> "hello" + str)
.orElseGet(() -> dontCallMe());
System.out.println(o);
}
private static String dontCallMe() {
System.out.println("should not have called");
return "why oh why";
}
Run Code Online (Sandbox Code Playgroud)
仅输出:
helloworld
Run Code Online (Sandbox Code Playgroud)
此处的区别在于,我们传递给该方法的事物(Supplier)将保持() -> dontCallMe()不变,它不会变为() -> "why oh why"-仅当您调用时get,它才真正评估那里发生的事情并dontCallMe真正被调用。
| 归档时间: |
|
| 查看次数: |
1414 次 |
| 最近记录: |