Java Stream collect() Method

The collect() method in Java, part of the java.util.stream.Stream interface, is used to perform a mutable reduction operation on the elements of the stream. This method is highly versatile and can be used to accumulate elements into a Collection, StringBuilder, or any other type of mutable container.

Table of Contents

  1. Introduction
  2. collect() Method Syntax
  3. Understanding collect()
  4. Examples
    • Basic Usage with Collectors
    • Using Custom Collector
  5. Real-World Use Case
  6. Conclusion

Introduction

The collect() method performs a mutable reduction operation on the elements of the stream using a Collector. This method is a terminal operation, meaning it consumes the stream and produces a result.

collect() Method Syntax

There are two main overloads of the collect() method:

  1. Using a Collector:

<R, A> R collect(Collector<? super T, A, R> collector)



2. **Using supplier, accumulator, and combiner:**
```java
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)

Parameters:

  • collector: The Collector describing the reduction.
  • supplier: A function that provides a new mutable result container.
  • accumulator: An associative, non-interfering, stateless function for incorporating an additional element into a result container.
  • combiner: An associative, non-interfering, stateless function for combining two result containers.

Returns:

  • The result of the reduction.

Throws:

  • This method does not throw any exceptions.

Understanding collect()

The collect() method is used to gather the elements of a stream into a container, such as a List, Set, or Map. It is highly flexible, allowing you to define custom reduction operations using a combination of supplier, accumulator, and combiner functions.

Examples

Basic Usage with Collectors

To demonstrate the basic usage of collect(), we will create a Stream of strings and use collect() to accumulate its elements into a List.

Example

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "cherry");

        // Collect the elements into a List
        List<String> list = stream.collect(Collectors.toList());

        // Print the list
        System.out.println(list);
    }
}

Output:

[apple, banana, cherry]

Using Custom Collector

This example shows how to use collect() with custom supplier, accumulator, and combiner functions to accumulate elements into a StringBuilder.

Example

import java.util.stream.Stream;

public class CustomCollectorExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "cherry");

        // Collect the elements into a StringBuilder
        StringBuilder stringBuilder = stream.collect(
            StringBuilder::new,  // Supplier
            (sb, s) -> sb.append(s).append(", "),  // Accumulator
            StringBuilder::append  // Combiner
        );

        // Print the StringBuilder
        System.out.println(stringBuilder);
    }
}

Output:

apple, banana, cherry,

Real-World Use Case

Collecting Employee Names into a List

In real-world applications, the collect() method can be used to collect employee names into a list from a stream of employee objects.

Example

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class EmployeeCollectExample {
    static class Employee {
        String name;
        int age;

        Employee(String name, int age) {
            this.name = name;
            this.age = age;
        }

        String getName() {
            return name;
        }
    }

    public static void main(String[] args) {
        Stream<Employee> employeeStream = Stream.of(
            new Employee("Alice", 30),
            new Employee("Bob", 25),
            new Employee("Charlie", 35)
        );

        // Collect employee names into a List
        List<String> employeeNames = employeeStream.map(Employee::getName).collect(Collectors.toList());

        // Print the list of employee names
        System.out.println(employeeNames);
    }
}

Output:

[Alice, Bob, Charlie]

Conclusion

The Stream.collect() method is used to perform a mutable reduction operation on the elements of the stream, gathering them into a container such as a List, Set, or Map. This method is particularly useful for collecting and transforming stream elements. By understanding and using this method, you can efficiently manage and process streams of values in your Java applications, accumulating results into various types of containers as needed.

Comments