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

如何在 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方法内进行求值.只有两个执行,因为第二个调用返回预期的非空值.在vargs解决方案中,在调用合并方法之前,将对所有返回值的方法进行求值.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...