What is Objects.requireNonNullElseGet in Java?

Overview

The requireNonNullElseGet method is a static method of the Objects class in Java that works as follows:

  • If the supplied object is null, then the return value is computed from the get() method of the Supplier interface passed to it as a parameter.
  • If the supplied object is not 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

Method signature

public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)

Parameters

  • T obj: object.
  • Supplier<? extends T> supplier: supplier of the non-null object to return if the passed object is null.

Example 1

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));
}
}

Example 2

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));
}
}

Free Resources