How to do an action if an optional boolean is true?

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.

7

It 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.

2

For 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:

  1. Optional.ofNullable(booleanValue) - Checks for null value
  2. .filter(p -> p).map(m -> callFunctionWhenTrue()) - Filter checks for boolean value true and appyly the map function
  3. .orElse(doSomethingWhenFalse()) - This part will execute if the boolean value is false
2

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.");}); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like