How to evaluate the next statement when null is returned in Java?

How do I execute the following JavaScript code in Java?

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

What I want to do is continue to evaluate the statement or method until it gets something instead of null

I want the caller code to be simple and effective

Solution

You can create a method for it

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

Code from: http://benjiweber.co.uk/blog/2013/12/08/null-coalescing-in-java-8/

Edit as described in the comments Find out how the following snippet uses it Using stream API has advantages over using vargs as method parameter If the value returned by a method is expensive, rather than being returned by a simple getter, the vargs solution will evaluate all of these methods first

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()));
}

yield

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

As shown in the output In stream solutions, methods that return values are evaluated within the coalesce method There are only two executions because the second call returns the expected non - null value In the vargs solution, all methods that return values are evaluated before calling the merge method

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>