0
0
JavaHow-ToBeginner · 3 min read

How to Use Stream Collect in Java: Simple Guide

In Java, the collect() method is used with streams to gather elements into a collection or a single result. It takes a Collector that defines how to accumulate, combine, and finish the collection process. Common collectors include Collectors.toList() and Collectors.toSet().
📐

Syntax

The collect() method is called on a stream and requires a Collector as an argument. The general syntax is:

  • stream.collect(Collector)

Here, Collector defines how to accumulate stream elements into a final container like a list, set, or map.

java
stream.collect(Collectors.toList());
💻

Example

This example shows how to collect a stream of strings into a list using collect() and Collectors.toList(). It prints the collected list.

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

public class StreamCollectExample {
    public static void main(String[] args) {
        List<String> fruits = Stream.of("apple", "banana", "cherry")
                                    .collect(Collectors.toList());
        System.out.println(fruits);
    }
}
Output
[apple, banana, cherry]
⚠️

Common Pitfalls

Common mistakes when using collect() include:

  • Forgetting to import Collectors.
  • Using collect() without a proper collector, causing compilation errors.
  • Trying to reuse a stream after terminal operation like collect(), which causes an error.

Always create a new stream if you need to collect again.

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

public class WrongCollect {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("a", "b", "c");
        // Wrong: no collector passed
        // List<String> list = stream.collect(); // Compilation error

        // Correct usage
        var list = stream.collect(Collectors.toList());
        System.out.println(list);

        // Wrong: reuse stream after collect
        // stream.collect(Collectors.toList()); // IllegalStateException
    }
}
Output
[a, b, c]
📊

Quick Reference

Collector MethodDescriptionExample Usage
Collectors.toList()Collects elements into a Liststream.collect(Collectors.toList())
Collectors.toSet()Collects elements into a Setstream.collect(Collectors.toSet())
Collectors.joining(", ")Concatenates elements into a String with separatorstream.collect(Collectors.joining(", "))
Collectors.toMap(keyMapper, valueMapper)Collects elements into a Mapstream.collect(Collectors.toMap(String::length, s -> s))

Key Takeaways

Use collect() with a Collector to gather stream elements into collections or results.
Common collectors include Collectors.toList() and Collectors.toSet().
Never reuse a stream after a terminal operation like collect().
Always import java.util.stream.Collectors to use collectors.
Choose the right collector based on the desired output type.