Hir*_*ino 9 java java-8 java-stream
如何在Java中执行类似以下JavaScript代码的操作?
var result = getA() || getB() || getC() || 'all of them were undefined!';
Run Code Online (Sandbox Code Playgroud)
我想要做的是继续评估语句或方法,直到它得到一些东西而不是null.
我希望调用者代码简单有效.
你可以为它创建一个方法.
public static <T> T coalesce(Supplier<T>... ts) {
return asList(ts)
.stream()
.map(t -> t.get())
.filter(t -> t != null)
.findFirst()
.orElse(null);
}
Run Code Online (Sandbox Code Playgroud)
代码取自:http://benjiweber.co.uk/blog/2013/12/08/null-coalescing-in-java-8/
编辑正如评论中所述.在下面找到一个小片段如何使用它.使用StreamAPI比使用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()));
}
Run Code Online (Sandbox Code Playgroud)
产量
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
Run Code Online (Sandbox Code Playgroud)
如输出中所示.在Stream解决方案中,将在coalesce方法内部评估返回值的方法.只执行两次,因为第二次调用返回预期non-null值.在vargs解决方案中,在coalesce调用方法之前,将评估返回值的所有方法.