Junior — Middle
What methods can be used to pass a lambda expression through the Optional class?
sobes.tech AI
Answer from AI
In Java, lambda expressions can be passed through the Optional class in several ways:
- Using the
ifPresentmethod — if the Optional contains a value, the lambda will be called with that value:
Optional<String> optional = Optional.of("Hello");
optional.ifPresent(value -> System.out.println(value));
- Using the
mapmethod — applies the lambda to the value inside the Optional and returns a new Optional:
Optional<String> optional = Optional.of("hello");
Optional<String> upper = optional.map(s -> s.toUpperCase());
- Using the
orElseGetmethod — takes a Supplier (a lambda with no parameters) that returns a value if the Optional is empty:
Optional<String> optional = Optional.empty();
String value = optional.orElseGet(() -> "default");
Thus, lambda expressions can be passed to Optional methods for processing or retrieving values if they are present.