MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/java/comments/1r7iv5p/objectsrequirenonnullelse/o6tecei/?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
2
You can even use Optionals and write
String city = Optional.ofNullable(form.getCity()) .orElse(defaultCity);
And you can even chain it, say the city is in a nested object like Form -> Address -> City
String city = Optional.ofNullable(form) .map(Form::getAddress) .map(Address::getCity) .orElse(defaultCity)
And when any part of the Optional chain is null, it will short circuit to the default value
View all comments
2
u/witness_smile Feb 22 '26
You can even use Optionals and write
And you can even chain it, say the city is in a nested object like Form -> Address -> City
And when any part of the Optional chain is null, it will short circuit to the default value