Home > Java > javaTutorial > body text

How to Efficiently Convert List of Objects to Optional in Java Streams?

Barbara Streisand
Release: 2024-10-23 16:16:02
Original
253 people have browsed it

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 to Optional and extracting the first Other value efficiently can be a challenge. While flatMap typically requires a return stream, the absence of stream() for Optional complicates matters.

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!