r/java • • Feb 17 '26

Objects.requireNonNullElse

I must have been living in a cave. I just discovered that this exists.
I can code

City city = Objects.requireNonNullElse(form.getCity(), defaultCity);

... instead of:

City city = form.getCity();

if(city == null){

city = defaultCity;

}

113 Upvotes

136 comments sorted by

View all comments

2

u/witness_smile Feb 22 '26

You can even use Optionals and write

String city = Optional.ofNullable(form.getCity())
    .orElse(defaultCity);

And you can even chain it, say the city is in a nested object like Form -> Address -> City

String city = Optional.ofNullable(form)
    .map(Form::getAddress)
    .map(Address::getCity)
    .orElse(defaultCity)

And when any part of the Optional chain is null, it will short circuit to the default value