In Java 8, I have a variable, holding an optional boolean.
I want an action to be executed, if the optional is not empty, and the contained boolean is true.
I am dreaming about something like ifPresentAndTrue, here a full example:
import java.util.Optional; public class X { public static void main(String[] args) { Optional<Boolean> spouseIsMale = Optional.of(true); spouseIsMale.ifPresentAndTrue(b -> System.out.println("There is a male spouse.")); } } 6 Answers
For good order
if (spouseIsMale.orElse(false)) { System.out.println("There is a male spouse."); } Clear.
7It is possible to achieve that behaviour with .filter(b -> b):
spouseIsMale.filter(b -> b).ifPresent(b -> System.out.println("There is a male spouse.")); However, it costs some brain execution time seconds to understand what is going on here.
2For those looking to write this without traditional if(condition){ //Do something if true; }
Optional.of(Boolean.True) .filter(Boolean::booleanValue) .map(bool -> { /*Do something if true;*/ }) All of the above answers combined:
spouseIsMale .filter(Boolean::booleanValue) .ifPresent( value -> System.out.println("There is a male spouse.") ); What I usually use is (I also check for the null value):
Optional.ofNullable(booleanValue).filter(p -> p).map(m -> callFunctionWhenTrue()).orElse(doSomethingWhenFalse()); This has three parts:
Optional.ofNullable(booleanValue)- Checks for null value.filter(p -> p).map(m -> callFunctionWhenTrue())- Filter checks for boolean value true and appyly the map function.orElse(doSomethingWhenFalse())- This part will execute if the boolean value is false
You can shrink it a little bit.
Optional<Boolean> spouseIsMale= Optional.of(true); spouseIsMale.ifPresent(v -> { if (v) System.out.println("There is a male spouse.");});