Empty stream and single element stream are very common use-cases, especially when you utilize the .flatMap()
. For example, here's how Optional.stream()
is implemented in Java-9:
public Stream<T> stream() {
if (!isPresent()) {
return Stream.empty();
} else {
return Stream.of(value);
}
}
So given the stream of Optionals you can unwrap them into the flat stream this way:
streamOfOptionals.flatMap(Optional::stream);
Here you create tons of empty streams as well as single element streams, so optimizing such cases looks very reasonable. In particular, Stream.empty()
unlike Stream.of()
does not create an empty array and does not create the spliterator (it reuses the same spliterator instance). Stream.of(T)
is also particularly optimized inside the StreamBuilderImpl
, so no array is allocated for single element.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…