I could not find a way to do the following with Java Optional :
if (SOME_OBJECT != null) { doSomething(SOME_OBJECT); } else { doSomethingElse(); }
Using Optional , I don't mean the average value replacing SOME_OBJECT == null with Optional.ofNullable(SOME_OBJECT).isPresent() , which is much longer than just checking if null.
What I would expect is something like:
Optional.ofNullable(SOME_OBJECT) .ifPresent(this::doSomething) .orElse(this::doSomethingElse);
I could not find an API like the one I just wrote. He exists? If so, then what is it? If not, why not? :)
The second part of the code looks like an anti-pattern :( Why? Perhaps the Java architects could not use this syntax specifically ...
java java-8 nullable optional
AlikElzin-kilaka
source share