Since Java 9 the methods requireNonNullElse
and requireNonNullElseGet
are part of the java.util.Objects
class.
The method requireNonNullElse
accepts two arguments.
The first argument is an object that will be returned if that object is not null
.
The second argument is an object to be returned when the first argument is null
.
With this method you can replace the following ternary operator if (a != null) ? a : b
(or if (a == null) ? b : a)
with Objects.requireNonNullElse(a, b)
.
The method requireNonNullElseGet
allows to define a Supplier
function as second argument.
The Supplier
is only invoked when the first argument is null
, so it is lazy and will only be invoked when the first argument is null
.