如果这个User对象有多个类似age需要求和的属性有没有便捷的方法
时间: 2024-03-21 22:40:07 浏览: 13
有的,可以使用Java Stream的reduce方法来实现。假设现在User对象除了age属性外,还有一个height属性,我们也希望对集合内所有User对象的height属性求和,可以按照以下方式实现:
```java
public class User {
private int age;
private int height;
public User(int age, int height) {
this.age = age;
this.height = height;
}
public int getAge() {
return age;
}
public int getHeight() {
return height;
}
}
List<User> userList = new ArrayList<>();
userList.add(new User(18, 170));
userList.add(new User(20, 175));
userList.add(new User(22, 180));
int sumAge = userList.stream().mapToInt(User::getAge).sum();
int sumHeight = userList.stream().mapToInt(User::getHeight).sum();
System.out.println("Sum of age: " + sumAge);
System.out.println("Sum of height: " + sumHeight);
int[] sum = userList.stream()
.reduce(new int[]{0, 0},
(acc, user) -> new int[]{acc[0] + user.getAge(), acc[1] + user.getHeight()},
(acc1, acc2) -> new int[]{acc1[0] + acc2[0], acc1[1] + acc2[1]});
System.out.println("Sum of age: " + sum[0]);
System.out.println("Sum of height: " + sum[1]);
```
输出结果为:
```
Sum of age: 60
Sum of height: 525
Sum of age: 60
Sum of height: 525
```
解释:使用reduce方法可以将集合内的每个User对象的age和height属性累加到一个int数组中,最终得到一个包含age和height的总和的int数组。reduce方法的第一个参数是初始值,这里使用两个0表示age和height的初始值都为0。第二个参数是一个Lambda表达式,用于定义如何将一个User对象的age和height属性累加到int数组中。第三个参数也是一个Lambda表达式,用于定义如何将两个int数组合并成一个int数组。