Collectors.grouping
时间: 2023-10-19 15:34:31 浏览: 91
Collectors.groupingBy is a static method in the java.util.stream.Collectors class that performs grouping operations on the elements of a stream. It allows you to group the elements based on a specific criterion or property.
Here's an example of how to use Collectors.groupingBy:
Suppose we have a list of Person objects, and we want to group them by their age:
```java
List<Person> people = Arrays.asList(
new Person("John", 25),
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Jane", 30)
);
Map<Integer, List<Person>> peopleByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
```
In this example, we use the Person::getAge method reference as the grouping criterion. The resulting map, `peopleByAge`, will have the age as the key and a list of people with that age as the value.
Hope that helps! Let me know if you have any more questions.
阅读全文