How to get the first non-null value in Java?
Here's the fast lane to get the first non-null value with Stream.of()
, filter(Objects::nonNull)
, and findFirst()
:
This line of code will return var1
, var2
, or var3
, each of which is assessed to be the first non-null value—firstNonNull
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:
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:
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:
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:
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:
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.
Was this article helpful?