Course contentsShow
← Java
Lesson 1616 of 2,87034. Collectors in DepthFree lesson

Supplier: Creating the Mutable Result Container

Learn how supplier() provides the initial mutable container that accumulates intermediate results during collection.

Supplier: Creating the Mutable Result Container

You'll learn how the supplier() function creates the initial mutable container that holds intermediate results as elements are collected.

What Is the Supplier?

When you use a collector like Collectors.toList() or Collectors.groupingBy(), the stream needs somewhere to accumulate results as it processes elements. The supplier is the function that creates this initial, empty container at the start of the collection operation.

Think of it like this: if collecting is like filling a bucket with water, the supplier is the factory that provides you with an empty bucket to begin with. Without that empty bucket, you'd have nowhere to pour the water!

The Supplier's Role in the Collector Interface

The Supplier<A> is the first component of the Collector interface. It's a simple function with no parameters that returns a new mutable result container of type A. This container will be modified as the stream processes elements.

Supplier<List<String>> supplier = ArrayList::new;
// This creates a new empty ArrayList each time it's called

For Collectors.toList(), the supplier creates a new ArrayList. For Collectors.toSet(), it creates a new HashSet. For Collectors.toMap(), it creates a new HashMap.

Why Mutable?

The container must be mutable because the collector will repeatedly modify it by adding elements, updating values, or merging results—especially important in parallel streams where multiple containers may be created and later combined.

Key Takeaway: The supplier function creates the initial empty mutable container that will accumulate results during stream collection—it's the starting point for every collection operation.