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
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
toList() vs. toUnmodifiableList()?
Unmodifiable List (toList())
Returns: An unmodifiable list (but not necessarily immutable).
Implementation Detail: The returned list may still allow modifications through the original collection.
Use Case:
If we don’t need to modify the list but don’t require strict immutability.
If we're okay with the underlying implementation potentially being mutable.
Used when we want to prevent modifications via this specific reference but don’t need a truly immutable list.
List<String> list = List.of("Alice", "Bob");
List<String> unmodifiableList = list.stream().collect(Collectors.toList());
// Modifications via unmodifiableList will fail. But, if it's backed by a
// mutable list, changes to the original source can reflect in unmodifiableList
unmodifiableList.add("Charlie"); // Throws UnsupportedOperationExceptionImmutable List (toUnmodifiableList())
Returns: A truly immutable list (Java 10+).
Implementation Detail: The list is explicitly created as immutable, ensuring no external modifications.
Use Case:
When we want absolute immutability, meaning even if the original source changes, this list won't.
When working in a concurrent environment to ensure thread safety.
Useful for returning API responses where data should not be modified by the consumer.
List<String> immutableList = List.of("Alice", "Bob")
.stream()
.collect(Collectors.toUnmodifiableList());// Guaranteed to be immutable, regardless of the source.
// Modification attempts will always fail
immutableList.add("Charlie"); // Throws UnsupportedOperationExceptionWhat is Function.identity()?
Function.identity()?Function.identity() is a built-in function in Java that returns the input as-is.
Function.identity()means use the element itself as the key.String::lengthprovides the value.
Equivalent Lambda Expression:
But Function.identity() is cleaner and more readable.
Aggregation and Summarization
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
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
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)
reducing(BinaryOperator<T>)
Reduces elements using custom logic
reducing(identity, BinaryOperator<T>)
Reduces elements with a default value
Last updated