Hirofumi Okino Hirofumi Okino - 4 years ago 185
Java Question

How can I evaluate next statement when null was returned in Java?

How can I do something like the following JavaScript code, in Java?

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


What I want to to do is to continue evaluating statements or methods, until it gets something instead of
null
.

I would like the caller code to be simple and effective.

Answer Source

You could 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 taken from: http://benjiweber.co.uk/blog/2013/12/08/null-coalescing-in-java-8/

edit As mentioned in the comments. Find below a small snippet how to use it. Using the Stream API has an advantage over using vargs as method parameter. If the values returned by the methods are costly and not returned by simple getters the vargs solution would evaluate all those 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()));
}

output

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 the Stream solution the methods returning the values will be evaluated inside the coalesce method. Only two are executed, as the second call returns the expected non-null value. In the vargs solution all methods returning the values are evaluated before the coalesce method is invoked.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download