groupingby
时间: 2023-11-22 08:53:46 浏览: 33
`groupingBy` 是一个 Java 8 中的 Collectors 类中的静态方法,它接受一个分类函数作为参数,将流中的元素按照分类函数的规则进行分组,并返回一个 `Map` 对象,其中键是分类的标准,值是属于该分类的元素列表。以下是一个示例:
假设我们有一个 `Person` 类,其中包含姓名和年龄两个属性:
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
我们可以创建一个 `List` 对象来存储多个 `Person` 对象,并使用 `groupingBy` 方法根据每个人的年龄将它们分组:
```java
List<Person> people = Arrays.asList(
new Person("Alice", 20),
new Person("Bob", 30),
new Person("Charlie", 20),
new Person("Dave", 25),
new Person("Eve", 30)
);
Map<Integer, List<Person>> peopleByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
System.out.println(peopleByAge);
```
输出:
```
{20=[Person{name='Alice', age=20}, Person{name='Charlie', age=20}], 25=[Person{name='Dave', age=25}], 30=[Person{name='Bob', age=30}, Person{name='Eve', age=30}]}
```
`groupingBy` 方法将 `Person::getAge` 作为分类函数,将 `people` 列表中的元素按照年龄分组,并返回一个 `Map<Integer, List<Person>>` 对象。在这个 `Map` 中,键是年龄,值是属于该年龄的 `Person` 对象列表。