Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
null
communitycreator

What is Objects.requireNonNullElseGet in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

RELATED TAGS

java
null
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring