Java IntStream collect() Method

The collect() method in Java, part of the java.util.stream.IntStream 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
    • Using collect() with 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 in IntStream:

  1. Using a Collector:
<R> R collect(Collector<? super Integer, A, R> collector)
  1. Using supplier, accumulator, and combiner:
<R> R collect(Supplier<R> supplier, ObjIntConsumer<R> 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

To demonstrate the basic usage of collect(), we will create an IntStream and use collect() to accumulate its elements into a List<Integer>.

Example

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

public class CollectExample {
    public static void main(String[] args) {
        IntStream intStream = IntStream.of(1, 2, 3, 4, 5);

        // Collect the elements into a List<Integer>
        List<Integer> list = intStream.boxed().collect(Collectors.toList());

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

Output:

[1, 2, 3, 4, 5]

Using collect() with Custom Collector

This example shows how to use collect() with a custom collector to accumulate elements into a StringBuilder.

Example

import java.util.stream.IntStream;

public class CustomCollectorExample {
    public static void main(String[] args) {
        IntStream intStream = IntStream.of(1, 2, 3, 4, 5);

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

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

Output:

1, 2, 3, 4, 5,

Real-World Use Case

Collecting Scores into a Map

In real-world applications, the collect() method can be used to collect scores into a Map with the student's name as the key and the score as the value.

Example

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ScoresToMapExample {
    public static void main(String[] args) {
        String[] students = {"Alice", "Bob", "Charlie", "David", "Eve"};
        int[] scores = {85, 92, 78, 88, 90};

        // Create a map of student names to scores
        Map<String, Integer> studentScores = IntStream.range(0, students.length)
            .boxed()
            .collect(Collectors.toMap(i -> students[i], i -> scores[i]));

        // Print the map
        System.out.println(studentScores);
    }
}

Output:

{Bob=92, Eve=90, Alice=85, Charlie=78, David=88}

Conclusion

The IntStream.collect() method is used to perform a mutable reduction operation on the elements of the stream. This method is particularly useful for gathering elements into a collection or any other mutable container. By understanding and using this method, you can efficiently manage and process streams of integer values in your Java applications.

Comments