Xk D
Xk D

Reputation: 21

How to convert Optional<List<A>> to Optional<List<B>>

Let's say I have a method:

B someMethod(A) {
    // ...
}

And I have an Optional<List<A>>, how can I convert it to Optional<List<B>>?

Upvotes: 0

Views: 64

Answers (1)

Misha
Misha

Reputation: 28133

Use Optional.map to change Optional of one thing to Optional of another:

import static java.util.stream.Collectors.toList;

Optional<List<B>> optListB = optListA.map(
        listOfA -> listOfA.stream()
                .map(SomeClass::someMethod)
                .collect(toList())
);

(assuming someMethod is a static method of SomeClass)

Upvotes: 1

Related Questions