Java groupingBy: Group Lists with Collectors

In Java, you can use the Collectors.groupingBy() method in the Stream API to group Lists. This method takes a Function as a parameter, which is used to define the grouping criteria, and then returns a Map object where the key is the grouping criteria and the value is a list of elements belonging to that group.

Here is a simple example demonstrating how to use the Collectors.groupingBy() method to group a List.

Let’s suppose there is a Student class:

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

And then we have a list:

List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 22));
students.add(new Student("Alice", 21));
students.add(new Student("Charlie", 20));

Now we want to group by the attribute of name in Student.

Map<String, List<Student>> groupedStudents = students.stream()
    .collect(Collectors.groupingBy(Student::getName));

This will result in a Map object where the key is the name attribute value of the Student, and the value is a list of Student objects belonging to that group.

In the example above, the possible outcome of groupedStudents could be like this:

{
    "Alice": [Student{name='Alice', age=20}, Student{name='Alice', age=21}],
    "Bob": [Student{name='Bob', age=22}],
    "Charlie": [Student{name='Charlie', age=20}]
}
bannerAds