Concat fixed number of Optionals to Stream

Viewed 85

I have 3 Optionals:

Optional<T> optA = getOptA();
Optional<T> optB = getOptB();
Optional<T> optC = getOptC();

Is there a better way to concat them to a Stream<T> than:

Stream.concat(Stream.concat(optA.stream(), optB.stream()), optC.stream());

If the number of optionals grows, this gets unwieldy very soon:

Stream.concat(Stream.concat(optA.stream(), optB.stream()), Stream.concat(optC.stream(), optD.stream());
1 Answers

What about using Stream::of and concat in using reduce:

Stream.of(optA.stream(), optB.stream(), optC.stream(), optD.stream())
        .reduce(Stream::concat)
        .orElseGet(Stream::empty);

Or you can use a map, and your code should be:

Stream.of(optA, optB, optC, optD)
        .map(Optional::stream)
        .reduce(Stream::concat)
        .orElseGet(Stream::empty);

Which lead you to combine map and reduce using only flatMap as mentioned in comments:

Stream.of(optA, optB, optC)
        .flatMap(Optional::stream);
Related