gpt4 book ai didi

java - 在 Java 中返回 null 时如何评估下一条语句?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:58 24 4
gpt4 key购买 nike

如何在 Java 中执行类似以下 JavaScript 代码的操作?

var result = getA() || getB() || getC() || 'all of them were undefined!';

我想做的是继续评估语句或方法,直到它得到一些东西而不是 null

我希望调用者代码简单有效。

最佳答案

您可以为它创建一个方法。

public static <T> T coalesce(Supplier<T>... ts) {
return asList(ts)
.stream()
.map(t -> t.get())
.filter(t -> t != null)
.findFirst()
.orElse(null);
}

代码取自:http://benjiweber.co.uk/blog/2013/12/08/null-coalescing-in-java-8/

编辑 如评论中所述。在下面找到一个小片段如何使用它。使用 Stream API 比使用 vargs 作为方法参数有优势。如果方法返回的值代价高昂并且不是由简单的 getter 返回,vargs 解决方案将首先评估所有这些方法。

import static java.util.Arrays.asList;
import java.util.function.Supplier;
...
static class Person {
String name;
Person(String name) {
this.name = name;
}
public String name() {
System.out.println("name() called for = " + name);
return name;
}
}

public static <T> T coalesce(Supplier<T>... ts) {
System.out.println("called coalesce(Supplier<T>... ts)");
return asList(ts)
.stream()
.map(t -> t.get())
.filter(t -> t != null)
.findFirst()
.orElse(null);
}

public static <T> T coalesce(T... ts) {
System.out.println("called coalesce(T... ts)");
for (T t : ts) {
if (t != null) {
return t;
}
}
return null;
}

public static void main(String[] args) {
Person nobody = new Person(null);
Person john = new Person("John");
Person jane = new Person("Jane");
Person eve = new Person("Eve");
System.out.println("result Stream API: "
+ coalesce(nobody::name, john::name, jane::name, eve::name));
System.out.println();
System.out.println("result vargas : "
+ coalesce(nobody.name(), john.name(), jane.name(), eve.name()));
}

输出

called coalesce(Supplier<T>... ts)
name() called for = null
name() called for = John
result Stream API: John

name() called for = null
name() called for = John
name() called for = Jane
name() called for = Eve
called coalesce(T... ts)
result vargas : John

如输出所示。在 Stream 解决方案中,返回值的方法将在 coalesce 方法内进行评估。仅执行两个,因为第二个调用返回预期的 non-null 值。在 vargs 解决方案中,所有返回值的方法都在调用 coalesce 方法之前进行评估。

关于java - 在 Java 中返回 null 时如何评估下一条语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34510831/

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