假设我们有一个 List<Person>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<Person> 转换为一个 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 集合中对象字段求和:流式 API 与传统方法

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

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