假设我们有一个List,Person对象有一个age属性,我们想要将所有Person对象的age属性求和,可以使用流式API和reduce方法来实现:

List<Person> persons = new ArrayList<>();
persons.add(new Person("John", 25));
persons.add(new Person("Jane", 30));
persons.add(new Person("Bob", 40));

int sumOfAges = persons.stream()
                      .mapToInt(Person::getAge)
                      .reduce(0, Integer::sum);

System.out.println("Sum of ages: " + sumOfAges); //输出 Sum of ages: 95

首先,我们将List转换为一个IntStream,使用mapToInt方法将每个Person对象的age属性转换为一个int值。然后,我们使用reduce方法将所有int值求和,初始值为0。

另外,如果我们使用Java 8之前的版本,可以使用foreach循环来实现:

List<Person> persons = new ArrayList<>();
persons.add(new Person("John", 25));
persons.add(new Person("Jane", 30));
persons.add(new Person("Bob", 40));

int sumOfAges = 0;
for (Person person : persons) {
    sumOfAges += person.getAge();
}

System.out.println("Sum of ages: " + sumOfAges); //输出 Sum of ages: 95

这种方式比较传统,但是代码比较冗长,而且不够优雅

java在List集合中对象的某个字段求和

原文地址: https://www.cveoy.top/t/topic/e0UF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录