Explain Codes LogoExplain Codes Logo

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

java
null-checks
coalesce
optional
Anton ShumikhinbyAnton Shumikhin·Oct 1, 2024
TLDR

Here's the fast lane to get the first non-null value with Stream.of(), filter(Objects::nonNull), and findFirst():

String firstNonNull = Stream.of(var1, var2, var3) .filter(Objects::nonNull) // "Who you gonna call? Not null busters!" .findFirst() // "First come, first serve." .orElse(null); // "Well, if all else fails..."

This line of code will return var1, var2, or var3, each of which is assessed to be the first non-null valuefirstNonNull will be null if all values turn out to be null.

From simple to advanced solutions

Using Apache Commons Lang

Enter Apache Commons Lang: the library's ObjectUtils.firstNonNull method is a readability champion:

String firstNonNull = ObjectUtils.firstNonNull(var1, var2, var3); // "There can be only one non-null Highlander!"

This is a fast and smooth ride for coalescing values sans explicit null checks.

Embracing Guava's minimalism

Guava's MoreObjects.firstNonNull enters the stage with its bare elegance:

String firstNonNull = MoreObjects.firstNonNull(var1, var2); // "First non-null for two? Guava got you covered!"

Use this cool move when you are already tapping into Guava's capacity in your project.

Adopting overloaded functions

You can roll your own method using overloaded functions imitating SQL's COALESCE:

public static <T> T coalesce(T... values) { for (T val : values) { if (val != null) { return val; // "Nulls need not apply!" } } return null; // "No non-null values? Return null, no hard feelings!" }

These tailor-made methods are adaptable to handle a variety of input types greatly enhancing readability and conciseness.

Other methods

The grace of Optional

Using Optional.ofNullable().orElse() is suitable for scenarios dealing with a single variable coalesce:

String firstNonNull = Optional.ofNullable(var1).orElse(var2); // "Optional to the rescue of single variables!"

This fluent way is both precise and expressive, eliminating unnecessary noise.

Jackson library

Until now, we didn't address the unknown terrain of JSON data. Meet Jackson library where you can build a custom deserializer to offer a similar effect using nonNull annotations:

public class NonNullDeserializer extends StdDeserializer<Object> { // Implement custom deserialization that coalesces nulls }

Remember efficiency

While dealing with multiple variables: according to sparsity or density of nulls in your values, the efficiency of the methods may differ. If nulls are few and far between a Stream filter is apt; conversely Apache Commons or your custom method might serve you better for a string of potential nulls.