Junior — Middle
Milliseid meetodeid saab kasutada funktsionaalse liidese edastamiseks Optional objekti sees?
sobes.tech AI
Vastus AI-lt
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
OptionalusingOptional.of()orOptional.ofNullable(), passing a lambda expression or a method reference. -
Use
Optionalmethods that accept functional interfaces, such asmap(),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.