Functional style of Java 8's Optional.ifPresent and if-not-Present?
The ifPresent()
and ifPresentOrElse()
methods of the Optional
class in Java 8 provide a functional style way to perform different actions depending on whether the Optional
object is empty or contains a value.
The ifPresent()
method takes a Consumer
object as an argument and invokes it with the value contained in the Optional
object if it is present. If the Optional
object is empty, ifPresent()
does nothing.
Here's an example of using ifPresent()
to print the value contained in an Optional
object:
Optional<String> opt = Optional.of("Hello");
opt.ifPresent(s -> System.out.println(s)); // prints "Hello"
The ifPresentOrElse()
method is similar to ifPresent()
, but it also takes a Runnable
object as an argument. If the Optional
object is empty, ifPresentOrElse()
invokes the Runnable
object. If the Optional
object is not empty, ifPresentOrElse()
invokes the Consumer
object with the value contained in the Optional
object.
Here's an example of using ifPresentOrElse()
to print a default message if the Optional
object is empty:
Optional<String> opt = Optional.empty();
opt.ifPresentOrElse(
s -> System.out.println(s),
() -> System.out.println("Optional is empty") // prints "Optional is empty"
);
I hope this helps! Let me know if you have any questions.