Home  >  Article  >  Java  >  How to Convert Optional to Stream in Java 8?

How to Convert Optional to Stream in Java 8?

DDD
DDDOriginal
2024-10-24 01:10:02606browse

How to Convert Optional to Stream in Java 8?

Converting Optional to Stream using Java 8's flatMap()

Java's Stream API offers concise coding solutions, but there are certain scenarios that may pose challenges. One such situation involves converting an Optional to a Stream using flatMap().

The Issue

Given a list of things (List things) and a method (Optional resolve(Thing thing)), the goal is to map the things to Optionals and retrieve the first Other. The conventional solution would be:

things.stream().flatMap(this::resolve).findFirst();

However, flatMap() expects a stream as a return value, while Optional doesn't provide a stream() method.

Java 16 Solution

Java 16 introduces Stream.mapMulti(), alleviating this issue:

Optional<Other> result =
    things.stream()
          .map(this::resolve)
          .<Other>mapMulti(Optional::ifPresent)
          .findFirst();

Java 9 Solution

Java 9 introduces Optional.stream(), enabling direct conversion:

Optional<Other> result =
    things.stream()
          .map(this::resolve)
          .flatMap(Optional::stream)
          .findFirst();

Java 8 Solution

Regrettably, Java 8 lacks a straightforward method to convert Optional to Stream. However, a helper function can be utilized:

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();

The above is the detailed content of How to Convert Optional to Stream in Java 8?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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