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

1

u/Known_Tackle7357 Feb 18 '26

And then after some time it will become City city = defaultCity; Optional<City> optionalCity = getCity(); If (optionalCity != null & optionalCity.isPresent()) { city = optionalCity.get(); }

Been there

2

u/White_C4 Feb 18 '26

If you need to check if Optional<City> field is not null, you're kind of defeating the point of not having a default value for it. Just set it to Optional.empty() then only do a optionalCity.isPresent() check every time.

1

u/Jaded-Asparagus-2260 Feb 18 '26

@NonNull Optional<City> getCity() {}.