How to group elements into a map using Collectors in Java

What is the Collectors class?

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, etc. The different functionalities in the Collectors 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 that helps group the input elements according to a classification function. 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.

The groupingBy() method is defined in the Collectors class. The Collectors class is defined in the java.util.stream package.

To import the Collectors class, use the following import statement:

import java.util.stream.Collectors;

Syntax


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

Parameters

  • Function<? super T, ? extends K> classifier: The classification function.

Return value

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

Code

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Map;
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"));
Map<Integer, List<Student>> groupedStudents = studentList.stream().collect(Collectors.groupingBy(s -> s.grade));
System.out.println("Grouped Students according to their grade - " + groupedStudents);
}
}

Explanation

In the code above,

  • Lines 1 to 4: We import the relevant classes.
  • Lines 8 to 24: We define a Student class that consists of the grade and name as fields. The class has a constructor that initializes the value of the fields and the toString() method.
  • Lines 27 to 31: We create a list of student objects.
  • Line 33: The student objects are grouped by the grade value with the help of the groupingBy() method. The classification function here returns the grade value for every Student object passed.
  • Line 34: We print the grouped student objects.

Free Resources