java在List集合中对象的某个字段求和
假设我们有一个List
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
另外,如果我们使用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
这种方式比较传统,但是代码比较冗长,而且不够优雅
原文地址: https://www.cveoy.top/t/topic/e0UF 著作权归作者所有。请勿转载和采集!