微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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.jb51.cc/java/121241.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐