通过一段程序来说明其差异:
public class OptionalTest {
static String B(){
System.out.println("B()...");
return "B";
}
public static void main(String[] args) {
System.out.println(Optional.of("A").orElse(B()));
}
}
执行结果为:
B()...
A
Process finished with exit code 0
public class OptionalTest {
static String B(){
System.out.println("B()...");
return "B";
}
public static void main(String[] args) {
System.out.println(Optional.of("A").orElseGet(()->B()));
}
}
执行结果为:
A
Process finished with exit code 0