r/java • u/edurbs • 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
View all comments
2
u/witness_smile Feb 22 '26
You can even use Optionals and write
And you can even chain it, say the city is in a nested object like Form -> Address -> City
And when any part of the Optional chain is null, it will short circuit to the default value