Home >Java >javaTutorial >How to Efficiently Convert List of Objects to Optional in Java Streams?
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:
<code class="java">Optional<Other> result = things.stream() .map(this::resolve) .<Other>mapMulti(Optional::ifPresent) .findFirst();</code>
Java 9 Solution
JDK 9 adds Optional.stream, simplifying the task:
<code class="java">Optional<Other> result = things.stream() .map(this::resolve) .flatMap(Optional::stream) .findFirst();</code>
Java 8 Solution
In Java 8, the following approach can be taken:
<code class="java">Optional<Other> result = things.stream() .map(this::resolve) .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) .findFirst();</code>
Using a helper function to convert Optional to Stream:
<code class="java">static <T> Stream<T> streamopt(Optional<T> opt) { if (opt.isPresent()) return Stream.of(opt.get()); else return Stream.empty(); } Optional<Other> result = things.stream() .flatMap(t -> streamopt(resolve(t))) .findFirst();</code>
The above is the detailed content of How to Efficiently Convert List of Objects to Optional in Java Streams?. For more information, please follow other related articles on the PHP Chinese website!