Junior — Middle
What methods can be used to pass a functional interface inside an object?
sobes.tech AI
Answer from AI
In Java, an Optional object can contain a functional interface, such as Supplier, Function, or Consumer. To pass a functional interface inside an Optional, you can:
-
Create an Optional using
Optional.of()orOptional.ofNullable(), passing a lambda expression or a method reference. -
Use Optional methods that accept functional interfaces, such as
map(),flatMap(),ifPresent().
Example of passing a functional interface into an Optional:
Optional<Supplier<String>> optionalSupplier = Optional.of(() -> "Hello, World!");
optionalSupplier.ifPresent(supplier -> {
System.out.println(supplier.get());
});
In this example, a functional interface Supplier is passed into the Optional, which returns a string when called.