How to get the first non-null value in Java?

JavaCoalesce

Java Problem Overview


Is there a Java equivalent of SQL's COALESCE function? That is, is there any way to return the first non-null value of several variables?

e.g.

Double a = null;
Double b = 4.4;
Double c = null;

I want to somehow have a statement that will return the first non-null value of a, b, and c - in this case, it would return b, or 4.4. (Something like the sql method - return COALESCE(a,b,c)). I know that I can do it explicitly with something like:

return a != null ? a : (b != null ? b : c)

But I wondered if there was any built-in, accepted function to accomplish this.

Java Solutions


Solution 1 - Java

Solution 2 - Java

No, there isn't.

The closest you can get is:

public static <T> T coalesce(T ...items) {
    for(T i : items) if(i != null) return i;
    return null;
}

For efficient reasons, you can handle the common cases as follows:

public static <T> T coalesce(T a, T b) {
    return a == null ? b : a;
}
public static <T> T coalesce(T a, T b, T c) {
    return a != null ? a : (b != null ? b : c);
}
public static <T> T coalesce(T a, T b, T c, T d) {
    return ...
}

Solution 3 - Java

If there are only two variables to check and you're using Guava, you can use MoreObjects.firstNonNull(T first, T second).

Solution 4 - Java

If there are only two references to test and you are using Java 8, you could use

Object o = null;
Object p = "p";
Object r = Optional.ofNullable( o ).orElse( p );
System.out.println( r );   // p

If you import static Optional the expression is not too bad.

Unfortunately your case with "several variables" is not possible with an Optional-method. Instead you could use:

Object o = null;
Object p = null;
Object q = "p";

Optional<Object> r = Stream.of( o, p, q ).filter( Objects::nonNull ).findFirst();
System.out.println( r.orElse(null) );   // p

Solution 5 - Java

Following on from LES2's answer, you can eliminate some repetition in the efficient version, by calling the overloaded function:

public static <T> T coalesce(T a, T b) {
    return a != null ? a : b;
}
public static <T> T coalesce(T a, T b, T c) {
    return a != null ? a : coalesce(b,c);
}
public static <T> T coalesce(T a, T b, T c, T d) {
    return a != null ? a : coalesce(b,c,d);
}
public static <T> T coalesce(T a, T b, T c, T d, T e) {
    return a != null ? a : coalesce(b,c,d,e);
}

Solution 6 - Java

This situation calls for some preprocessor. Because if you write a function (static method) which picks the first not null value, it evaluates all items. It is problem if some items are method calls (may be time expensive method calls). And this methods are called even if any item before them is not null.

Some function like this

public static <T> T coalesce(T ...items)

should be used but before compiling into byte code there should be a preprocessor which find usages of this „coalesce function“ and replaces it with construction like

a != null ? a : (b != null ? b : c)

Update 2014-09-02:

Thanks to Java 8 and Lambdas there is possibility to have true coalesce in Java! Including the crucial feature: particular expressions are evaluated only when needed – if earlier one is not null, then following ones are not evaluated (methods are not called, computation or disk/network operations are not done).

I wrote an article about it Java 8: coalesce – hledáme neNULLové hodnoty – (written in Czech, but I hope that code examples are understandable for everyone).

Solution 7 - Java

You can try this:

public static <T> T coalesce(T... t) {
    return Stream.of(t).filter(Objects::nonNull).findFirst().orElse(null);
}

Based on this response

Solution 8 - Java

With Guava you can do:

Optional.fromNullable(a).or(b);

which doesn't throw NPE if both a and b are null.

EDIT: I was wrong, it does throw NPE. The correct way as commented by Michal Čizmazia is:

Optional.fromNullable(a).or(Optional.fromNullable(b)).orNull();

Solution 9 - Java

Just for completness, the "several variables" case is indeed possible, though not elegant at all. For example, for variables o, p, and q:

Optional.ofNullable( o ).orElseGet(()-> Optional.ofNullable( p ).orElseGet(()-> q ) )

Please note the use of orElseGet() attending to the case that o, p, and q are not variables but expressions either expensive or with undesired side-effects.

In the most general case coalesce(e[1],e[2],e[3],...,e[N])

coalesce-expression(i) ==  e[i]  when i = N
coalesce-expression(i) ==  Optional.ofNullable( e[i] ).orElseGet(()-> coalesce-expression(i+1) )  when i < N

This can generate expressions excessively long. However, if we are trying to move to a world without null, then v[i] are most probably already of type Optional<String>, as opposed to simply String. In this case,

result= o.orElse(p.orElse(q.get())) ;

or in the case of expressions:

result= o.orElseGet(()-> p.orElseGet(()-> q.get() ) ) ;

Furthermore, if you are also moving to a functional-declarative style, o, p, and q should be of type Supplier<String> like in:

Supplier<String> q= ()-> q-expr ;
Supplier<String> p= ()-> Optional.ofNullable(p-expr).orElseGet( q ) ;
Supplier<String> o= ()-> Optional.ofNullable(o-expr).orElseGet( p ) ;

And then the whole coalesce reduces simply to o.get().

For a more concrete example:

Supplier<Integer> hardcodedDefaultAge= ()-> 99 ;
Supplier<Integer> defaultAge= ()-> defaultAgeFromDatabase().orElseGet( hardcodedDefaultAge ) ;
Supplier<Integer> ageInStore= ()-> ageFromDatabase(memberId).orElseGet( defaultAge ) ;
Supplier<Integer> effectiveAge= ()-> ageFromInput().orElseGet( ageInStore ) ;

defaultAgeFromDatabase(), ageFromDatabase(), and ageFromInput() would already return Optional<Integer>, naturally.

And then the coalesce becomes effectiveAge.get() or simply effectiveAge if we are happy with a Supplier<Integer>.

IMHO, with Java 8 we will see more and more code structured like this, as it's extremely self-explainatory and efficient at the same time, especially in more complex cases.

I do miss a class Lazy<T> that invokes a Supplier<T> only one time, but lazily, as well as consistency in the definition of Optional<T> (i.e. Optional<T>-Optional<T> operators, or even Supplier<Optional<T>>).

Solution 10 - Java

How about using suppliers when you want to avoid evaluating some expensive method?

Like this:

public static <T> T coalesce(Supplier<T>... items) {
for (Supplier<T> item : items) {
	T value = item.get();
	if (value != null) {
		return value;
	}
	return null;
}

And then using it like this:

Double amount = coalesce(order::firstAmount, order::secondAmount, order::thirdAmount)

You can also use overloaded methods for the calls with two, three or four arguments.

In addition, you could also use streams with something like this:

public static <T> T coalesce2(Supplier<T>... s) {
	return Arrays.stream(s).map(Supplier::get).filter(Objects::nonNull).findFirst().orElse(null);
}

Solution 11 - Java

Since Java 9 there is builtin Objects.requireNonNullElse method for two parameter coalesce. That was the most useful for me.

Solution 12 - Java

How about:

firstNonNull = FluentIterable.from(
    Lists.newArrayList( a, b, c, ... ) )
        .firstMatch( Predicates.notNull() )
            .or( someKnownNonNullDefault );

Java ArrayList conveniently allows null entries and this expression is consistent regardless of the number of objects to be considered. (In this form, all the objects considered need to be of the same type.)

Solution 13 - Java

Object coalesce(Object... objects)
{
	for(Object o : object)
		if(o != null)
			return o;
	return null;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfroadieView Question on Stackoverflow
Solution 1 - JavaAndrzej PolisView Answer on Stackoverflow
Solution 2 - Javales2View Answer on Stackoverflow
Solution 3 - JavaDaveView Answer on Stackoverflow
Solution 4 - JavaChristian UllenboomView Answer on Stackoverflow
Solution 5 - JavaEricView Answer on Stackoverflow
Solution 6 - JavaFrantaView Answer on Stackoverflow
Solution 7 - JavaLucas LeónView Answer on Stackoverflow
Solution 8 - JavaJamolView Answer on Stackoverflow
Solution 9 - JavaMario RossiView Answer on Stackoverflow
Solution 10 - JavaTriquiView Answer on Stackoverflow
Solution 11 - JavaMert ÜlkgünView Answer on Stackoverflow
Solution 12 - JavaLonnieView Answer on Stackoverflow
Solution 13 - JavaEricView Answer on Stackoverflow