Java LongStream collect() Method

The collect() method in Java, part of the java.util.stream.LongStream interface, is used to perform a mutable reduction operation on the elements of the stream using a Collector. This method is useful when you need to accumulate the elements of the stream into a collection or other mutable container.

Table of Contents

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

Introduction

The collect() method performs a reduction operation on the elements of a LongStream, resulting in a single summary result. This method is highly flexible and can be used to gather elements into various types of collections, or even create custom summary results.

collect() Method Syntax

The syntax for the collect() method is as follows:

<R> R collect(Supplier<R> supplier, ObjLongConsumer<R> accumulator, BiConsumer<R, R> combiner)

Parameters:

  • supplier: A function that provides a new result container.
  • accumulator: A function that folds a value into a result container.
  • combiner: A function that accepts two partial results and merges them.

Returns:

  • The result of the reduction.

Throws:

  • This method does not throw any exceptions.

Understanding collect()

The collect() method involves three main components:

  • Supplier: A function that creates an initial result container.
  • Accumulator: A function that incorporates an element into a result container.
  • Combiner: A function that merges two result containers, useful in parallel stream operations.

Examples

Basic Usage

To demonstrate the basic usage of collect(), we will create a LongStream and collect the elements into a List<Long>.

Example

import java.util.ArrayList;
import java.util.List;
import java.util.stream.LongStream;

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

        // Use collect() to collect elements into a List<Long>
        List<Long> list = longStream.collect(
            ArrayList::new, // Supplier
            List::add, // Accumulator
            List::addAll // Combiner
        );

        // Print the elements of the list
        list.forEach(System.out::println);
    }
}

Output:

1
2
3
4
5

Using a Custom Collector

This example shows how to use a custom collector to collect the elements of a LongStream into a custom container.

Example

import java.util.HashSet;
import java.util.Set;
import java.util.stream.LongStream;

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

        // Use collect() to collect elements into a Set<Long>
        Set<Long> set = longStream.collect(
            HashSet::new, // Supplier
            Set::add, // Accumulator
            Set::addAll // Combiner
        );

        // Print the elements of the set
        set.forEach(System.out::println);
    }
}

Output:

1
2
3
4
5

Real-World Use Case

Collecting Transaction Amounts into a List

In real-world applications, the collect() method can be used to collect transaction amounts from a LongStream into a List<Long> for further processing or analysis.

Example

import java.util.ArrayList;
import java.util.List;
import java.util.stream.LongStream;

public class CollectTransactionsExample {
    public static void main(String[] args) {
        LongStream transactionAmounts = LongStream.of(1000L, 2000L, 1500L, 3000L, 2500L);

        // Use collect() to collect elements into a List<Long>
        List<Long> transactions = transactionAmounts.collect(
            ArrayList::new, // Supplier
            List::add, // Accumulator
            List::addAll // Combiner
        );

        // Print the elements of the list
        transactions.forEach(System.out::println);
    }
}

Output:

1000
2000
1500
3000
2500

Conclusion

The LongStream.collect() method is used to perform a mutable reduction operation on the elements of the stream using a Collector. This method is particularly useful for accumulating the elements of a stream into a collection or other mutable container. By understanding and using this method, you can efficiently manage and process streams of values in your Java applications, ensuring that elements are collected and accumulated as needed.

Comments