Trusted answers to developer questions

How to count elements in each group using Collectors in Java

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

Overview

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.

What is 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.

Syntax


public static <T, K, A, D> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream)

Parameters

  • 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.

Return value

This method returns a Collector that groups the elements based on the classificationFunction.

Example

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;
}
@Override
public 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);
}
}

Explanation

  • Lines 1–5: We import the relevant classes.
  • Lines 8–24: We define a 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.
  • Lines 28–32: We create a list of student objects.
  • Line 34: We define the classificationFunction because it returns the grade value for every Student object passed.
  • Line 36: We use 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.
  • Line 37: We print the returned map.

RELATED TAGS

java
Did you find this helpful?