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
1
u/OwnBreakfast1114 Feb 19 '26 edited Feb 19 '26
Replacing null checks with optional wrapping is not bad, but not even close to the best use case. The best use case would be actually using flatMap and map.
as a very simple example you can imagine. Flatmap captures places where it can shift between non-empty -> empty, and map is always non-empty -> non-empty (not actually true in java.util.Optional, but conceptually should be used that way)
The chaining can't always be realized depending on how much control you need between steps, but the signatures are still correct either way. Your methods should take in non-null inputs, and flatMap/map should be used to decide whether to even invoke them or not.