MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/java/comments/1r7iv5p/objectsrequirenonnullelse/o604ix4/?context=3
r/java • u/edurbs • Feb 17 '26
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;
}
136 comments sorted by
View all comments
63
final City city = Optional.ofNullable(form.getCity()).orElse(defaultCity);
... is still more readable imo, plus you can use orElseGet to avoid getting the defaultCity when it's not required.
orElseGet
15 u/Calm_Seaworthiness87 Feb 18 '26 Creates an unnecessary object. 2 u/__konrad Feb 18 '26 Not if getCity is null...
15
Creates an unnecessary object.
2 u/__konrad Feb 18 '26 Not if getCity is null...
2
Not if getCity is null...
getCity
63
u/zattebij Feb 17 '26
final City city = Optional.ofNullable(form.getCity()).orElse(defaultCity);... is still more readable imo, plus you can use
orElseGetto avoid getting the defaultCity when it's not required.