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
  • 46,063
  • 13
  • 87
  • 137
Jelly Orns
  • 187
  • 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
  • 8,097
  • 4
  • 63
  • 97
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,087
  • 6
  • 41
  • 61
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,470
  • 4
  • 32
  • 59
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
  • 195,030
  • 44
  • 313
  • 345