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."));
}
}
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? ).
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).
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 ( = ).
For good order
if (spouseIsMale.orElse(false)) {
System.out.println("There is a male spouse.");
}
Clear.
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.
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;*/ })
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