Java groupBy: Grouping List Elements
In Java, the List’s groupBy method typically refers to using the groupBy method in the Stream API to group elements in a List. It specifically involves grouping elements in the List based on a specified condition and returning a Map object where the key is the grouping condition and the value is a list of elements that meet that condition.
For instance, assume there is a List containing multiple student objects, each with name and age properties. By using the groupBy method to group them based on age, students of the same age can be placed into the same list. This makes it easier to classify and analyze the data.
The example code is shown below:
List<Student> students = Arrays.asList(
new Student("Alice", 20),
new Student("Bob", 22),
new Student("Charlie", 20),
new Student("David", 21)
);
Map<Integer, List<Student>> groupedByAge = students.stream()
.collect(Collectors.groupingBy(Student::getAge));
groupedByAge.forEach((age, studentList) -> {
System.out.println("Students with age " + age + ":");
studentList.forEach(student -> {
System.out.println("- " + student.getName());
});
});
The above code groups student objects by age and outputs a list of students corresponding to each age group. Using the groupBy method can help simplify code logic, improve code readability, and maintainability.