The requireNonNullElseGet
method is a static method of the Objects
class in Java that works as follows:
null
, then the return value is computed from the get()
method of the Supplier
interface passed to it as a parameter.null
, then the object is returned as-is.This method was introduced in Java 8.
To use the requireNonNull
method, import the following module.
java.util.Objects
public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)
T obj
: object.Supplier<? extends T> supplier
: supplier of the non-null object to return if the passed object is null
.In the code below, null
is sent to the method as the object. An empty list of Object
is then returned.
import java.util.Collections;import java.util.List;import java.util.Objects;import java.util.function.Supplier;public class Main {public static void main(String[] args) {System.out.println(Objects.requireNonNullElseGet(null, (Supplier<List<Object>>) Collections::emptyList));}}
In the code below, a non-null object is passed to the method, and the method returns the passed object.
import java.util.Collections;import java.util.List;import java.util.Objects;import java.util.function.Supplier;public class Main {public static void main(String[] args) {String s = "hello";System.out.println(Objects.requireNonNullElseGet(s, (Supplier<List<Object>>) Collections::emptyList));}}