0% found this document useful (0 votes)
6 views

Collect Method in Java Streams

Uploaded by

happymailtosri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Collect Method in Java Streams

Uploaded by

happymailtosri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Java 8 Stream API: collect() Method

Introduction
The collect() method in Java 8's Stream API is a terminal operation used to transform the
elements of a stream into a different form, such as a List, Set, Map, or even a custom
container. It is one of the most powerful and versatile operations in the Stream API,
enabling complex data transformations and aggregations.

Basic Syntax and Variants


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

This method collects the elements of the stream using a Collector. The Collector is a utility
for gathering elements into a desired result container. The most common way to use
collect() is with the predefined collectors available in the Collectors utility class.

Common Predefined Collectors

To List:
List<T> resultList = stream.collect(Collectors.toList());

Example:
List<String> list = Stream.of("a", "b", "c").collect(Collectors.toList());
System.out.println(list); // Output: [a, b, c]

To Set:
Set<T> resultSet = stream.collect(Collectors.toSet());

Example:
Set<String> set = Stream.of("a", "b", "c").collect(Collectors.toSet());
System.out.println(set); // Output: [a, b, c]

To Map:
Map<K, V> resultMap = stream.collect(Collectors.toMap(keyMapper, valueMapper));

Example:
Map<String, Integer> map = Stream.of("a", "bb", "ccc")
.collect(Collectors.toMap(Function.identity(), String::length));
System.out.println(map); // Output: {a=1, bb=2, ccc=3}

Joining:
String result = stream.collect(Collectors.joining());

Example:
String joined = Stream.of("a", "b", "c").collect(Collectors.joining(", "));
System.out.println(joined); // Output: a, b, c

Summarizing:
IntSummaryStatistics summary =
stream.collect(Collectors.summarizingInt(Integer::intValue));

Example:
IntSummaryStatistics stats = Stream.of(1, 2, 3, 4,
5).collect(Collectors.summarizingInt(Integer::intValue));
System.out.println(stats); // Output: IntSummaryStatistics{count=5, sum=15, min=1,
average=3.000000, max=5}

Grouping By:
Map<K, List<T>> groupedBy = stream.collect(Collectors.groupingBy(classifier));

Example:
Map<Integer, List<String>> groupedByLength = Stream.of("a", "bb", "ccc", "dd")
.collect(Collectors.groupingBy(String::length));
System.out.println(groupedByLength); // Output: {1=[a], 2=[bb, dd], 3=[ccc]}

Partitioning By:
Map<Boolean, List<T>> partitionedBy =
stream.collect(Collectors.partitioningBy(predicate));

Example:
Map<Boolean, List<String>> partitionedByLength = Stream.of("a", "bb", "ccc")
.collect(Collectors.partitioningBy(s -> s.length() > 1));
System.out.println(partitionedByLength); // Output: {false=[a], true=[bb, ccc]}

Custom Collectors
If the predefined collectors do not meet your needs, you can create custom collectors using
the Collector interface.

Example of a Custom Collector:

Collector<String, StringBuilder, String> customCollector = Collector.of(


StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString
);
String result = Stream.of("a", "b", "c").collect(customCollector);
System.out.println(result); // Output: abc

Detailed Explanation
1. Supplier: Provides a new mutable result container.
2. Accumulator: Adds an element to the result container.
3. Combiner: Merges two result containers.
4. Finisher: Performs the final transformation from the intermediate result container to the
final result type.
5. Characteristics: Defines the collector’s characteristics such as CONCURRENT,
UNORDERED, and IDENTITY_FINISH.

Summary
The collect() method in Java Streams is a versatile tool for gathering and transforming
stream elements. Using predefined collectors from the Collectors utility class covers most
common use cases, while custom collectors allow for more specialized data processing
needs. Understanding how to use collect() effectively can greatly enhance your ability to
process data using the Stream API.

You might also like