8

I couldn't find a way to do the following with Java's Optional:

if (SOME_OBJECT != null) {
  doSomething(SOME_OBJECT);
} else {
  doSomethingElse();
}

By using Optional, I don't mean mean replacing SOME_OBJECT == null with Optional.ofNullable(SOME_OBJECT).isPresent(), which a much longer syntax than simply checking if null.

What I would expect is something like:

Optional.ofNullable(SOME_OBJECT)
  .ifPresent(this::doSomething)
  .orElse(this::doSomethingElse);

I couldn't find an API like the one I just wrote. Does it exist? If so, what is it? If not, why not? :)

The second piece of code looks like an anti-pattern :( Why? Perhaps Java's architects prevented this syntax on purpose...

8
  • 1
    It does seem surprising ifPresent doesn't return the Optional, and that there doesn't seem to be an ifAbsent. Apr 23, 2017 at 15:34
  • 4
    I think the second piece of code might be an anti-pattern because it does three method calls, and seems to do more checks as well (ifPresent and orElse must re-check the result of ofNullable. It seems at least as complicated as an if-then to read and would be somewhat harder to maintain. All downside (even if small), no upside.
    – markspace
    Apr 23, 2017 at 15:36
  • @markspace: I tend to feel that way about Optional as a whole. :-) But I haven't used it in anger (I haven't done any serious Java in years now), so my opinion there is reactionary and uninformed... :-) Apr 23, 2017 at 15:39
  • 2
    @T.J.Crowder I think Optional was introduced as part of the streaming implementation. It's used under the hood in streams to prevent NullPointerExceptions. From that point of view I think it makes sense -- as part of a larger cohesive framework. Randomly sprinkling your code with Optional probably isn't going to have a cohesive effect on its design or implementation, you'd need some good reason to use these sorts of objects.
    – markspace
    Apr 23, 2017 at 15:48
  • 3
    If you already have a variable which contains null just keep your if and be happy. There is nothing to be gained to wrap it into an Optional for a single condition.
    – eckes
    Apr 23, 2017 at 17:37

3 Answers 3

9

As mentioned in this Blog Article, Optionals will get a new method in Java 9: void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction). So, with Java, 8 you don't have something like that at the moment.

2
4

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

You can either update now to the Java 9 Early Access build, or you can build the method yourself with the following:

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

As said Java 8 does not have a construct to do exactly what you want.

I know, it's ugly, far less readable than a simple if/then/else but you can do this:

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 have always return something.
Or on the other hand you can handle cleanly the case isPresent().

Optional.ofNullable(someObject).ifPresent(obj -> {
  System.out.println("present");
});
2
  • While possible, I can't think of a situation where this would be a good idea. It is way more complicated than the if-else, and the unused return values further obfuscate the intent. (In addition to abusing map() and orElseGet() for side effects).
    – Hulk
    Apr 24, 2017 at 8:38
  • Right... I was just trying to understand if we can avoid this limitation only with Java 8. But the result is a little bit too ugly :)
    – freedev
    Apr 24, 2017 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.