Course contentsShow
← Java
Lesson 1515 of 2,87033. Streams API: Terminal OperationsFree lesson

The Three-Argument collect Overload

Using collect(Supplier, BiConsumer, BiConsumer) to build custom collection logic without creating a full Collector implementation.

The Three-Argument collect Overload

What you'll learn: How to build custom collection logic directly using collect(Supplier, BiConsumer, BiConsumer) without implementing the full Collector interface.

Understanding the Simpler collect Form

While the Collector interface (from the previous lesson) provides a powerful abstraction, sometimes you need something simpler for one-off collection tasks. Java provides a three-argument collect overload that lets you specify collection logic inline:

<R> R collect(Supplier<R> supplier,
              BiConsumer<R, ? super T> accumulator,
              BiConsumer<R, R> combiner)

The Three Arguments Explained

Think of this like giving assembly instructions:

  1. Supplier: Creates the container (like getting an empty box)
  2. Accumulator: Adds each element to the container (like placing items in the box)
  3. Combiner: Merges two containers together (for parallel stream support)

Practical Example

// Collecting strings into a StringBuilder
StringBuilder result = stream.collect(
    StringBuilder::new,           // Create empty StringBuilder
    StringBuilder::append,         // Add each string
    StringBuilder::append          // Merge two StringBuilders
);

This is equivalent to creating a full Collector but much more concise for simple cases.

When to Use This Form

Use the three-argument collect when:

  • You need custom collection logic for a specific case
  • The standard collectors (like toList()) don't fit your needs
  • Creating a full Collector implementation feels like overkill

The supplier creates the result container, the accumulator processes each element into that container, and the combiner handles parallel execution by merging partial results.

Key Takeaway: The three-argument collect overload provides a lightweight way to define custom collection behavior inline without implementing the full Collector interface—perfect for simple, one-off collection tasks.