Accumulator: Adding Elements to the Container
You'll learn how the accumulator() method defines the logic that adds each stream element into the mutable container.
The Core Idea
In the previous lesson, you learned that the Supplier creates an empty container. Now the accumulator() comes into play—it returns a BiConsumer<A, T> that takes the container (type A) and a stream element (type T) and incorporates that element into the container.
Think of it like an assembly line: the supplier built you an empty box, and now the accumulator is the worker who takes each item coming down the conveyor belt and places it into that box. The accumulator is called once for every single element in the stream.
How It Works
The accumulator() method signature looks like this:
BiConsumer<A, T> accumulator()
Ais the type of the mutable container (likeArrayList)Tis the type of the stream elements- The
BiConsumertakes both and mutates the container by adding the element
For a simple list collector, the accumulator might look like:
BiConsumer<List<String>, String> accumulator = (list, element) -> list.add(element);
This lambda takes the list and each string element, then adds the element to the list. It doesn't return anything—it just modifies the container in place.
The Pattern
Every time the stream processes an element, it calls:
accumulator.accept(container, streamElement);
This happens sequentially for each element, building up your result container piece by piece.
Key Takeaway: The accumulator() defines a BiConsumer that mutates the mutable container by incorporating each stream element—it's the workhorse that actually builds your collected result one element at a time.