Java 8 stream operation on empty list

You will get a empty collection. As collect is explained in doc:

Performs a mutable reduction operation on the elements of this stream using a Collector.

and the mutable reduction:

A mutable reduction operation accumulates input elements into a mutable result container, such as a Collection or StringBuilder, as it processes the elements in the stream.

You will get a empty collection because of the origin input is empty or due to the filter operation.

Thanks for @Andy Turner 's tips.

It's the fact that toList() accumulates into a new list that means it doesn't return null.

And the doc gets explain for the Collectors.toList() with this:

Returns a Collector that accumulates the input elements into a new List.

We can get from the source code

    public static <T>
    Collector<T, ?, List<T>> toList() {
        return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
                                   (left, right) -> { left.addAll(right); return left; },
                                   CH_ID);
    }

that it will never make a null output but you can still get a null with customized Collector as Andy shows.


collect is a terminal operation, so it must be evaluated.

When terminating a Stream pipeline with collect(Collectors.toList()), you'll always get an output List (you'll never get null). If the Stream is empty (and it doesn't matter if it's empty due to the source of the stream being empty, or due to all the elements of the stream being filtered out prior to the terminal operation), the output List will be empty too.