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/OwnBreakfast1114 Feb 19 '26

It was always weird to me that equals takes a "preferred" object. Equals always feels like a "no special argument" type of method. I think the new type classes will actually make it far more sensible, but I'm not sure how they'll work with subtyping.