firstNonNull()
is a ObjectUtils
class that is used to return the first non-null value from a list of objects.
ObjectUtils
The definition of ObjectUtils
can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the [Maven Repository](https://mvnrepository.com/artifact/org.apache.commons/commons-la ng3).
You can import the ObjectUtils
class as follows:
import org.apache.commons.lang3.ObjectUtils;
public static <T> T firstNonNull( T... values)
values
: The list of objects to test.
This method returns the first value that isn’t null. Otherwise, the method returns null
if all the values are null
or if the array is null
or empty.
import org.apache.commons.lang3.ObjectUtils;import java.util.Arrays;public class Main {public static void main(String[] args) {String[] strings = {null, "hi", null, null, "hello"};System.out.printf("The output of ObjectUtils.firstNonNull() for the string - '%s' is '%s'", Arrays.toString(strings), ObjectUtils.firstNonNull(strings));System.out.println();strings = new String[]{null, null, null};System.out.printf("The output of ObjectUtils.firstNonNull() for the string - '%s' is '%s'", Arrays.toString(strings), ObjectUtils.firstNonNull(strings));System.out.println();strings = null;System.out.printf("The output of ObjectUtils.firstNonNull() for the string - '%s' is '%s'", Arrays.toString(strings), ObjectUtils.firstNonNull(strings));System.out.println();strings = new String[0];System.out.printf("The output of ObjectUtils.firstNonNull() for the string - '%s' is '%s'", Arrays.toString(strings), ObjectUtils.firstNonNull(strings));System.out.println();}}
The output of the code will be as follows:
The output of ObjectUtils.firstNonNull() for the string - '[null, hi, null, null, hello]' is 'hi'
The output of ObjectUtils.firstNonNull() for the string - '[null, null, null]' is 'null'
The output of ObjectUtils.firstNonNull() for the string - 'null' is 'null'
The output of ObjectUtils.firstNonNull() for the string - '[]' is 'null'
objects = [null, "hi", null, null, "hello"]
The method returns hi
, the first non-null value in the array.
objects = null
The method returns false
because the array/list of objects points to null
.
objects = [null, null, null]
The method returns null
because all the values in the array/list of objects point to null
.
objects = []
The method returns null
because the array/list of objects is empty.