1. Overview
In this article, we will look at 2 different methods of Optional class. These methods are helpful in taking an action on value, if value is present in Optional.
This article is part of ongoing series of Optional. Read about it more here.
2. ifPresent family
ifPresent family consists of 2 different methods.
- ifPresent​(Consumer<? super T> action)
- ifPresentOrElse​(Consumer<? super T> action, Runnable emptyAction)
3. ifPresent​(Consumer<? super T> action)
ifPresent method accepts a Consumer to perform an action on value if value is present in Optional. This method can be useful to log the result using logger.
This method is equivalent to a “if condition” applied on a result.
Optional<String> opt = … // Method returns Optional opt.ifPresent(value -> logger.log(LogLevel.INFO, value));
4. ifPresentOrElse​(Consumer<? super T> action, Runnable emptyAction)
ifPresentOrElse method was added in Java 9. This method is similar to ifPresent method except for, it provides a mechanism to handle else part of the if condition.
opt.ifPresentOrElse​( value -> logger.log(LogLevel.INFO, value), () -> System.out.println("No Value Present"));
You can also log the result if value is absent.
opt.ifPresentOrElse​( value -> logger.log(LogLevel.INFO, value), () -> logger.log(LogLevel.WARN, "Value absent"));
5. Which method to use?
It depends on the use-case which method to use. If no action is needed for the absent value then go with ifPresent​ method else use ifPresentOrElse​.
6. Conclusion
In this article, we discussed 2 different methods that provides us to perform an action if value is present or absent. We also discussed under which circumstances this method should be used.