How to use groupBy in Java streams?
In Java, the groupBy method of Stream can be used to perform grouping operations on the elements in the Stream. The groupBy method takes a Function as a parameter, which is used to extract the key value of the elements and returns a Map object where the key is the value of the grouping and the value is a list of elements belonging to that group.
For example:
Suppose we have a List containing Person objects, each Person object having an age property, and we want to group them by age.
List<Person> persons = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 25),
new Person("David", 30)
);
Map<Integer, List<Person>> groupedByAge = persons.stream()
.collect(Collectors.groupingBy(Person::getAge));
groupedByAge.forEach((age, people) -> {
System.out.println("Age " + age + ": " + people);
});
In this example, we start by converting the List to a Stream using the stream method, then we group the elements using the collect and groupingBy methods. Finally, we iterate through each group using the forEach method and print the results.
Note: In the example above, the Person class needs to implement a getAge method to retrieve the age attribute.