How to perform an action if the optional boolean type is true?

In Java 8, I have a variable containing an optional boolean type.

I want the action to be executed if the optional parameter is not empty, and the boolean contained in it is true.

I dream of something like ifPresentAndTrue, here is a complete 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."));
  }
}
+11
source share
6 answers

For good order

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

To clear.

+20
source

You can achieve this behavior with .filter(b → b):

spouseIsMale.filter(b -> b).ifPresent(b -> System.out.println("There is a male spouse."));

However, in order to understand what is happening here, it takes a few seconds to complete the brain.

+6
source

:

spouseIsMale
.filter(Boolean::booleanValue)
.ifPresent(
  value -> System.out.println("There is a male spouse.")
);
+3

, if(condition){//Do something if true; } if(condition){//Do something if true; }

Optional.of(Boolean.True)
    .filter(Boolean::booleanValue)
        .map(bool -> { /*Do something if true;*/ })
+2
source

You can reduce it a little.

Optional<Boolean> spouseIsMale= Optional.of(true);
spouseIsMale.ifPresent(v -> { if (v) System.out.println("There is a male spouse.");});
0
source

Usually I use (I also check for a null value):

Optional.ofNullable(booleanValue).filter(p -> p).map(m -> callFunctionWhenTrue()).orElse(doSomethingWhenFalse());

It has three parts:

  1. Optional.ofNullable(booleanValue) - Checks a null value
  2. .filter(p -> p).map(m -> callFunctionWhenTrue()) - The filter checks the boolean value true and applies the map function
  3. .orElse(doSomethingWhenFalse()) - this part will be executed if the boolean value is false
0
source

Source: https://habr.com/ru/post/1687541/


All Articles