In Java, Collectors
is a utility class that provides various implementations of reduction operations such as grouping elements, collecting elements to different collections, summarizing elements according to various criteria, and more. The different functionalities in this class are usually used as the final operation on streams.
groupingBy()
method?groupingBy()
is a static method of the Collectors
class used to return a Collector
, which is used to group the input elements according to a classificationFunction
. The elements are mapped to a key as classified by the classification function. All the elements for the same key will be stored in a List
. All the keys with the respective elements in the List
will be stored in a Map
.
This method accepts a downstream Collector
that is applied to the grouped values associated with a key.
For example, consider the following list of integers:
[1,2,2,4,2,1,2,4,6,3,21,4,6,75,3,224,2,35]
groupingBy()
and counting()
are used to get the count of each distinct integer.
public static <T, K, A, D> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream)
Function<? super T, ? extends K> classifier
: This is the classification function.Collector<? super T, A, D> downstream
: This is the collector implementing downstream reduction operation.This method returns a Collector
that groups the elements based on the classificationFunction
.
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.Map;import java.util.function.Function;public class Main {static class Student{int grade;String name;public Student(int grade, String name) {this.grade = grade;this.name = name;}@Overridepublic String toString() {return "Student{" +"grade=" + grade +", name='" + name + '\'' +'}';}}public static void main(String[] args){List<Student> studentList = Arrays.asList(new Student(2, "sam"),new Student(2, "john"),new Student(4, "john"),new Student(4, "Lilly"),new Student(5, "mason"));Function<Student, Integer> classificationFunction = student -> student.grade;Map<Integer, Long> groupedStudents = studentList.stream().collect(Collectors.groupingBy(classificationFunction, Collectors.counting()));System.out.println("Number of students in each group grouped according to their grade - " + groupedStudents);}}
Student
class consisting of the grade
and name
as fields. The class has a constructor that initializes the value of the fields and the toString()
method.list
of student
objects.classificationFunction
because it returns the grade
value for every Student
object passed.groupingBy()
and counting()
to calculate the count of students in different grades. We pass the classificationFunction
as the argument to groupingBy()
method. Once the student objects are grouped, the counting()
method counts the number of students in each group. It returns a map of grade
and group count.