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 (Java 8) and ifPresentOrElse() method (Java 9+) of the Optional class 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. Both methods return void, making them suitable for side-effects only.
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. Use ifPresentOrElse when you need to perform side-effects for both cases, rather than orElse or orElseGet, which are designed for returning fallback values.
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.