1. Introduction
In Java, groupingBy is a powerful and flexible operation provided by the Stream API. It is used to group elements of the stream by a certain property into a Map. This operation is useful for aggregating elements in a collection based on a characteristic.
2. Program Steps
1. Create a List of objects.
2. Use the Stream API and Collectors.groupingBy() to group the elements by a certain property.
3. Print the resulting Map to the console.
3. Code Program
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return name + ": " + age;
}
}
public class ListGroupingByExample {
public static void main(String[] args) {
// Step 1: Create a List of objects
List<Student> students = List.of(
new Student("John", 20),
new Student("Jane", 22),
new Student("Bob", 20),
new Student("Alice", 22)
);
// Step 2: Use Stream API and Collectors.groupingBy() to group the elements by a certain property
Map<Integer, List<Student>> studentsByAge = students.stream()
.collect(Collectors.groupingBy(Student::getAge));
// Step 3: Print the resulting Map to the console
System.out.println(studentsByAge);
}
}
Output:
{20=[John: 20, Bob: 20], 22=[Jane: 22, Alice: 22]}
4. Step By Step Explanation
Step 1: We initialize a List of Student objects, each having a name and an age.
Step 2: We utilize the stream() method to convert the list into a Stream, and then apply the Collectors.groupingBy() collector to group the elements of the stream by the age property. This returns a Map where the key is the age, and the value is a List of Student objects having that age.
Step 3: Finally, we print out the resulting Map to the console, showing the students grouped by their age.