1

I want to convert an Optional<T> to a Stream<T>:

  • If the optional does hold a value, the stream contains that value.
  • If the optional does not hold a value, the stream should be empty.

I came up with the following:

public static Stream<T> stream(Optional<T> optional) {
    return optional.map(Stream::of).orElseGet(Stream::empty);
}

Is there a shorter way?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Jelly Orns
  • 197
  • 1
  • 2
  • 8

4 Answers4

1

Upgrade to Java 9, you have a method there: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#stream--

public Stream<T> stream​()

If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.

Since: 9

Honza Zidek
  • 9,204
  • 4
  • 72
  • 118
1
Optional.of(10).map(Stream::of).orElseGet(Stream::empty);

In Java9 the missing stream method has been added, so the code would have been written like so,

optional.stream()
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
0

Your code return Stream<Stream<T>>. Try change to this

public static <T> Stream<T> stream(Optional<T> optional) {
    return optional
            .map(t -> Stream.of(t))
            .orElseGet(Stream::empty);
}
Hadi J
  • 16,989
  • 4
  • 36
  • 62
0

The code you posted does not compile. Why did you use an additional Stream.of(...)? This works:

public static <T> Stream<T> stream(Optional<T> optional) {
    return optional.map(Stream::of).orElseGet(Stream::empty);
}
Jesper
  • 202,709
  • 46
  • 318
  • 350