3

I am very new to programming so be gentle please! :D

public void test(Optional<String> testString){
    testString.ifPresent(s -> {
        //do stuff...
        System.out.println("Exit method");
        return;
    });
    //Log if it was not present
    Logger.log("...");
}

Here you have a code snippet. If the optional is present I do some stuff and want to exit the method by just calling return. I now wonder why my logger logs something although the testString is present. Can someone maybe point out what I'm missing please ? Thank you !

2 Answers 2

2

The problem is that when you do:

 testString.ifPresent(s -> {
        //do stuff...
        System.out.println("Exit method");
        return;
    });

You return from a lambda function, and not from the test(), as you expect.

Try using isPresent:

    if (testString.isPresent()) {
        System.out.println("Exit method");
        return;
    }
    //Log if it was not present
    System.out.println("Not present");
5
  • Oh I see, thanks for pointing out. Is there a way to end the test method from within the lambda ?
    – IonicBlaze
    Sep 7, 2016 at 19:22
  • 1
    The only way I'm aware of is to throw a RuntimeException of some kind. Not nice. Sep 7, 2016 at 19:25
  • Alright, I will go with your suggestion then. Thank you very much! :)
    – IonicBlaze
    Sep 7, 2016 at 19:26
  • 1
    You can use CompleteableFuture to wait for computations in lambdas, including async ones.
    – the8472
    Sep 7, 2016 at 22:24
  • That's an excellent idea, I think you should post it as an alternative. Sep 8, 2016 at 18:03
2

With Java 9 Optional will have the method

void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)

which handles the else part aswell. For now you should stick with the already accepted answer.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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.