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

Show parent comment

6

u/Dry_Try_6047 Feb 17 '26

Ehh ... from.getCity() != null ? from.getCity() : defaultCity ... I don't find this too bad. Missing elvis operator doesn't bother me day-to-day

2

u/pragmatick Feb 18 '26

It's more helpful when you chain getter calls.

1

u/unknowinm Feb 18 '26

I do from.hasCity() ? from.getCity() : defaultCity

or if the code gets repetitive, I create a helper function inside from

City getCityOr(City city){ return hasCity() ? getCity(): city}

then just call it a million times

from.getCityOr(defaultCity)

1

u/Jaded-Asparagus-2260 Feb 18 '26

I love Python's walrus operator for this:

City city = (City fromCity := from.getCity()) != null ? fromCity : defaultCity;