gaurav agarwal
gaurav agarwal

Reputation: 451

Java 8 stream operation on empty list

I am just wondering what will be behavior of Java 8 stream on empty list.

List<?> emptyList = new ArrayList<>();
List<?> processedList = emptyList.stream().collect(Collectors.toList());

Will this be empty list or null?

I know streams do lazy propagation, so in this case will call go to collect() method or just it will end at stream() method?

Upvotes: 42

Views: 85523

Answers (2)

Lebecca
Lebecca

Reputation: 2878

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.

Upvotes: 8

Eran
Eran

Reputation: 393791

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.

Upvotes: 59

Related Questions