Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 491
Hirofumi Okino Avatar asked Dec 29 '15 12:12

Hirofumi Okino


People also ask

How do you handle if condition is null?

Use the ISNULL function with the IF statement when you want to test whether the value of a variable is the null value. This is the only way to test for the null value since null cannot be equal to any value, including itself. The syntax is: IF ISNULL ( expression ) ...

How do you check if a return is null?

The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.

Can we compare null values in Java?

We can simply compare the string with Null using == relational operator. Print true if the above condition is true.


2 Answers

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.

like image 194
SubOptimal Avatar answered Oct 26 '22 09:10

SubOptimal


If you really want to use java8 stream API, then look at the SubOptimal's solution.

In pure Java, you can't write the same line as in javascript: java will be more verbose.

If your getter is not time/resource consuming and you do not care about calling them twice, you can do:

String result = getA() != null ? getA() :
    (getB() != null ? getB() :
       (getC() != null ? getC() :
           "default value"));

Else you can do it with plain if:

String result = getA();
if (result == null) {
    result = getB();
    if (result == null) {
        result = getC();
        if (result == null) {
             result = "default value";
        }
    }
}
like image 35
fluminis Avatar answered Oct 26 '22 07:10

fluminis