Collectors: Collection Operations.
Explore mutable reduction techniques in Java 8 using the Stream API collect() method. Understand how to apply predefined Collectors for common tasks such as collecting elements into lists, sets, maps, and performing advanced operations like grouping, partitioning, and mapping to streamline data processing.
In the earlier lesson, we discussed some immutable reduction methods. In this lesson, we will discuss mutable reduction methods.
Mutable reductions
The mutable reductions collect the desired results into a mutable container object, such as a java.util.Collection or an array.
The mutable reduction is achieved through the collect() method. It is one of the Java 8 Stream API’s terminal methods.
There are two overloaded versions of the collect() method:
-
collect(Collector<? super T,A,R> collector) -
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)
This lesson focuses on the collect() method which takes an instance of Collector as input.
We have two options:
-
We can create our own
Collectorimplementation. -
We can use the predefined implementations provided by the
Collectorsclass.
Before discussing the collect() method further, we will first discuss the Collectors class in detail and look at how its methods are used with the collect() method to reduce streams.