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;
}
111
Upvotes
View all comments
Show parent comment
1
u/john16384 Feb 18 '26
It's not so much the one liner aspect, but the single assignment aspect as a reason to do this. Using a multiline switch expression or ternary spread over multiple lines is also good (only a single assignment).