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

前端之家收集整理的这篇文章主要介绍了在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解决方案中,在调用合并方法之前,将对所有返回值的方法进行求值.

原文链接:https://www.f2er.com/java/121241.html

猜你在找的Java相关文章