Collectors Utility Class

About

In Java, the Collectors class is a part of the java.util.stream package and provides a variety of utility methods to perform reduction operations on streams. These methods are used to accumulate elements from a stream into a collection or to summarize elements in various ways.

Basic Syntax

stream.collect(Collectors.someCollectorMethod());
  • stream → The Stream we want to collect data from.

  • collect(Collectors.someMethod()) → Applies a reduction operation.

Collecting into Lists, Sets, and Maps

Method
Description

toList()

Collects elements into an unmodifiable List

toUnmodifiableList()

Returns an immutable List

toSet()

Collects elements into an unmodifiable Set

toUnmodifiableSet()

Returns an immutable Set

toMap(keyMapper, valueMapper)

Collects elements into a Map (throws error for duplicate keys)

toMap(keyMapper, valueMapper, mergeFunction)

Collects into a Map, merging duplicates

toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)

Collects into a custom Map implementation

What is Function.identity()?

Aggregation and Summarization

Method
Description

counting()

Counts the number of elements

summarizingInt(ToIntFunction<T>)

Returns IntSummaryStatistics (count, min, max, sum, avg)

summarizingDouble(ToDoubleFunction<T>)

Returns DoubleSummaryStatistics

summarizingLong(ToLongFunction<T>)

Returns LongSummaryStatistics

maxBy(Comparator<T>)

Returns the maximum element

minBy(Comparator<T>)

Returns the minimum element

reducing(BinaryOperator<T>)

Performs a general reduction

Joining Strings

Method
Description

joining()

Concatenates elements into a single string

joining(delimiter)

Joins elements with a delimiter

joining(delimiter, prefix, suffix)

Joins with a delimiter, prefix, and suffix

Grouping & Partitioning

Method
Description

groupingBy(classifier)

Groups elements into a Map<K, List<T>>

groupingBy(classifier, collector)

Groups with a custom downstream collector

groupingBy(classifier, supplier, collector)

Groups elements into a custom Map implementation

partitioningBy(predicate)

Splits elements into two groups (true/false)

partitioningBy(predicate, downstream)

Splits elements into two groups (true/false) with a downstream collector

Custom Reduction (reducing)

Method
Description

reducing(BinaryOperator<T>)

Reduces elements using custom logic

reducing(identity, BinaryOperator<T>)

Reduces elements with a default value

Last updated