"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Convert List of Objects to Optional in Java Streams?

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

Published on 2024-11-07
Browse:334

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:

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();
Release Statement This article is reprinted at: 1729667949 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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