Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."));
  }
}
like image 478
slartidan Avatar asked Oct 16 '17 08:10

slartidan


People also ask

How do you know if Boolean is optional?

Optional binding The code let booleanValue = booleanValue returns false if booleanValue is nil and the if block does not execute. If booleanValue is not nil , this code defines a new variable named booleanValue of type Bool (instead of an optional, Bool? ).

How do you use Boolean true?

TRUE is a reference to an object of the class Boolean, while true is just a value of the primitive boolean type. Classes like Boolean are often called "wrapper classes", and are used when you need an object instead of a primitive type (for example, if you're storing it in a data structure).

How do you make a Boolean equal true?

boolean user = true; So instead of typing int or double or string, you just type boolean (with a lower case "b"). After the name of you variable, you can assign a value of either true or false. Notice that the assignment operator is a single equals sign ( = ).


3 Answers

For good order

if (spouseIsMale.orElse(false)) {
    System.out.println("There is a male spouse.");
}

Clear.

like image 141
Joop Eggen Avatar answered Oct 27 '22 14:10

Joop Eggen


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.

like image 37
slartidan Avatar answered Oct 27 '22 15:10

slartidan


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;*/ })
like image 41
Sanjay K S Avatar answered Oct 27 '22 15:10

Sanjay K S