gpt4 book ai didi

java - Java 8 中可选的 ofNullable 执行流程

转载 作者:搜寻专家 更新时间:2023-11-01 01:42:48 25 4
gpt4 key购买 nike

我注意到如果我按以下方式使用 Optional:

Object returnValue = Optional.ofNullable(nullableValue)
.map(nonNullValue -> firstMethod(arg1, nonNullValue))
.orElse(secondMethod)

当nullableValue 不为null 时,它正在执行第一个方法和第二个方法。难道我做错了什么?我希望它仅在 nullableValue 不为 null 时执行 firstMethod。

map 和 flatMap 似乎有前置条件(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() 不是像 map 调用那样调用 secondMethod() 的那个。您传递的是 secondMethod() 的返回值,而不是方法本身。

你想做什么:

Optional.ofNullable(nullableValue).map(MyClass::firstMethod).orElseGet(MyClass::secondMethod);

它的作用是将 secondMethod 转换为供应商。这样它仅在可选为空时调用。

关于java - Java 8 中可选的 ofNullable 执行流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25578269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com