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;
}
112
Upvotes
View all comments
Show parent comment
12
u/aoeudhtns Feb 17 '26
really at this point the
Objects#requireNonNullfamily of functions are best for this example.Optionalshould be reserved mostly to do function chaining.Here's the choices, basically, besides the ternary.