Sobes.tech
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:

  1. Create an Optional using Optional.of() or Optional.ofNullable(), passing a lambda expression or a method reference.

  2. 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.