Java Stream collect() Example

1. Introduction

The collect() method in the Java Streams API is a versatile and powerful tool used to transform the elements of a stream into a different form, typically a collection like a List, Set, or a Map. It is one of the most flexible operations within the Stream API, enabling developers to accumulate elements from a stream into a container of their choice or perform mutable fold operations. This method is particularly useful for gathering results after performing operations such as filtering, mapping, or sorting on a stream.

Key Points

1. collect() is a terminal operation that transforms the output of a stream into a collection or other data structure.

2. It often uses predefined collectors from the Collectors utility class, including methods like toList(), toSet(), and toMap().

3. Custom collectors can be created to perform more complex aggregation operations.

2. Program Steps

1. Import necessary Java classes.

2. Create a stream of elements.

3. Apply transformations and collect the results.

4. Display the collected results.

3. Code Program

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

public class StreamCollectExample {

    public static void main(String[] args) {
        // Step 2: Create a stream of elements
        Stream<String> namesStream = Stream.of("John", "Jane", "Adam", "Alice", "Bob");

        // Step 3: Collect results into a list
        List<String> namesList = namesStream.collect(Collectors.toList());

        // Additional collection types for demonstration
        Set<String> namesSet = namesList.stream()
                                        .filter(name -> name.startsWith("A"))
                                        .collect(Collectors.toSet());

        // Step 4: Display the results
        System.out.println("Names List: " + namesList);
        System.out.println("Names Set (starting with 'A'): " + namesSet);
    }
}

Output:

Names List: [John, Jane, Adam, Alice, Bob]
Names Set (starting with 'A'): [Adam, Alice]

Explanation:

1. Stream Creation: A Stream of String objects is created from a hardcoded array. Streams provide a high-level abstraction for processing sequences of elements.

2. Collection into List: The stream elements are collected into a List using Collectors.toList(), which gathers all input elements and stores them in an ArrayList.

3. Filtering and Collecting into Set: An additional example demonstrates converting a list to a stream, applying a filter to retain only names that start with 'A', and collecting the results into a Set to eliminate duplicates and demonstrate different collection strategies.

4. Output: The results are printed to the console, showing how elements from the stream are first collected into a list and then into a set after filtering. This illustrates the versatility of the collect() method in collecting and transforming stream elements into various types of collections.

5. Use in Applications: The collect() method is crucial in real-world applications for data manipulation and aggregation tasks. It allows developers to gather processed data into common data structures, making it easier to integrate stream processing results into application logic.


Comments