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 !
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With