Java 8 实现一次性聚合对象多个列的值
时间: 2023-12-27 07:05:37 浏览: 37
Java 8提供了Stream API,可以使用它来进行一次性聚合对象的多个列的值。下面是一个示例代码,假设有一个Person类,其中有name、age、gender三个属性:
```
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("Alice", 20, "female"),
new Person("Bob", 30, "male"),
new Person("Charlie", 25, "male"),
new Person("David", 25, "male"),
new Person("Eva", 20, "female")
);
// 按照age聚合,并且计算每个年龄段的人数和平均年龄
persons.stream()
.collect(Collectors.groupingBy(Person::getAge, Collectors.summarizingInt(Person::getAge)))
.forEach((age, summary) -> System.out.println("Age: " + age + ", Count: " + summary.getCount() + ", Average Age: " + summary.getAverage()));
}
}
class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
}
```
这段代码将Person对象按照age属性进行聚合,然后使用Collectors.summarizingInt方法对每个年龄段的Person对象进行统计,得到每个年龄段的人数和平均年龄。最后,使用forEach方法将结果输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)