Can I use Java to control the flow?

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 ...

+7
java java-8 nullable optional
source share
3 answers

As mentioned in this blog article, Options will get a new Methode in Java 9 void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction); , so with Java 8 you do not have something like this at the moment.

+8
source share

As already mentioned, Java 8 has no construct to do exactly what you want.

I know this is ugly, much less readable than simple if / then / else, but you can do it:

 Optional.ofNullable(someObject) .map(obj -> { System.out.println("present"); return obj; }) .orElseGet(() -> { System.out.println("not present"); return null; }); 

The only side effect is that you always return something.
Or, on the other hand, you can cleanly handle the isPresent() case.

 Optional.ofNullable(someObject).ifPresent(obj -> { System.out.println("present"); }); 
+2
source share

As stated in BdoubleB97 (Bdubzz), Java 9 implements Optional#ifPresentOrElse , which will accept a Consumer<T> , which will be applied if Optional<T> present, and Runnable , which will be executed if Optional<T> empty.

Now you can either upgrade Java 9 Early Access, or create a method yourself as follows:

 public <T> void ifPresentOrElse(Optional<T> optional, Consumer<? super T> action, Runnable emptyAction) { if (optional.isPresent()) { action.accept(optional.get()); } else { emptyAction.run(); } } 
+2
source share

All Articles