An empty stream and a stream of individual elements are very common use cases, especially if you use .flatMap()
. For example, here Optional.stream()
implemented in Java-9:
public Stream<T> stream() { if (!isPresent()) { return Stream.empty(); } else { return Stream.of(value); } }
Therefore, given the options stream, you can expand them into a flat stream as follows:
streamOfOptionals.flatMap(Optional::stream);
Here you create a lot of empty threads, as well as threads of individual elements, so the optimization of such cases looks very reasonable. In particular, Stream.empty()
, unlike Stream.of()
does not create an empty array and does not create a spliterator (it reuses the same instance of spliterator). Stream.of(T)
also especially optimized inside StreamBuilderImpl
, therefore an array is not allocated for one element.
source share