Becoming Concise with Java 8's Optional and Stream::flatMap
When working with Java 8 streams, transforming a List
Java 16 Solution
Java 16 introduces Stream.mapMulti, enabling a more concise approach:
Optional result = things.stream()
.map(this::resolve)
.mapMulti(Optional::ifPresent)
.findFirst();
Java 9 Solution
JDK 9 adds Optional.stream, simplifying the task:
Optional result = things.stream()
.map(this::resolve)
.flatMap(Optional::stream)
.findFirst();
Java 8 Solution
In Java 8, the following approach can be taken:
Optional result = things.stream()
.map(this::resolve)
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.findFirst();
Using a helper function to convert Optional to Stream:
static Stream streamopt(Optional opt) {
if (opt.isPresent())
return Stream.of(opt.get());
else
return Stream.empty();
}
Optional result = things.stream()
.flatMap(t -> streamopt(resolve(t)))
.findFirst();
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3