[英]Optional ofNullable execution flow in java 8
我注意到如果我使用Optional可以通过以下方式:
Object returnValue = Optional.ofNullable(nullableValue)
.map(nonNullValue -> firstMethod(arg1, nonNullValue))
.orElse(secondMethod)
当nullableValue不为null时,它正在执行第一个方法和第二个方法。 难道我做错了什么? 当nullableValue不为null时,我希望它只执行firstMethod。
map和flatMap似乎有preCondition( if(!isPresent()
)。但是,orElse没有。如何在不使用if not null条件的情况下使用java8编写代码?
根据评论, 示例代码 :
public static String firstMethod(String someString) {
System.out.println("In first method");
return someString;
}
public static String secondMethod() {
System.out.println("In second method");
return "secondMethod";
}
public static void main(String a[]) {
String nullableString = "nonNullString";
String result = Optional.ofNullable(nullableString)
.map(nonNullString -> firstMethod(nonNullString))
.orElse(secondMethod());
System.out.println("Result: "+result);
}
输出:
In first method
In second method
Result: nonNullString
您正在调用第二个方法作为参数传递给orElse()
调用。 orElse()
不是调用secondMethod()
那个,就像在map
调用中发生的一样。 您从secondMethod()
传递返回的值而不是方法本身。
你想做什么:
Optional.ofNullable(nullableValue).map(MyClass::firstMethod).orElseGet(MyClass::secondMethod);
这样做是将secondMethod转换为供应商。 这样,只有当optional为null时才会调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.