5

Is there a prettier way of doing the following in Java 8, avoiding isPresent and get?

void doStuff(String someValue, Optional<Boolean> doIt) {
    if (doIt.isPresent()) {
        if (doIt.get()) {
            trueMethod(someValue);
        } else {
            falseMethod(someValue);
        }
    }
}

I tried using map, without success. But I probably didn't try hard enough?

neu242
  • 15,796
  • 20
  • 79
  • 114
  • 4
    Probably it's not a good design to use `Optional` as method parameter. See [this answer](http://stackoverflow.com/a/23464794/4856258) by OpenJDK developer. – Tagir Valeev Jun 16 '15 at 07:10
  • I agree with @Tagir Valeev. I expect that, since this function does nothing when `doIt` is empty, you've given us an oversimplified version of the function. The best option is probably to provide an override. – Jacob Zimmerman Jun 29 '15 at 13:10

2 Answers2

6

You can use ifPresent instead of isPresent and get :

void doStuff(String someValue, Optional<Boolean> doIt) {
    doIt.ifPresent (b -> {
                             if (b) 
                                 trueMethod(someValue);  
                             else
                                 falseMethod(someValue);
                         });
}

EDIT: fixed my code, since you can't use the ternary operator if trueMethod and falseMethod don't return anything.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

This would be the functional approach using map:

Function<Boolean, Void> logic = isTrue -> {
  if (isTrue) trueMethod(someValue);
  else falseMethod(someValue);
  return null;
};
doIt.map(logic);

However, it is really ugly, mostly because of your "not-very-functional" trueMethod/falseMethod, which both return void (leading to the ugly return null).

Rahel Lüthy
  • 6,837
  • 3
  • 36
  • 51