简体   繁体   English

java lambda:如何计算列表中的项目总数?

[英]java lambda:How to count total items in a list?

How can I return the following result by lambda? 如何通过lambda返回以下结果?

int total = 0;
for (User user : userList) {
    total += user.getAge();
}

I know reduce's use. 我知道减少使用。 new LinkedList<Integer>().stream().reduce(0, (acc, x) -> acc + x)
I want to try(but failed). 我想尝试(但失败了)。 userList.stream().reduce(0, (acc, x) -> acc.getAge() + x.getAge());

You can use mapToInt 您可以使用mapToInt

useList
    .stream()
    .mapToInt(User::getAge)
    .sum();

If you really wanted to use reduce , here it is (but I don't see a point in using it as the above is more readable) 如果您真的想使用reduce ,那么就在这里(但我看不出使用它的意义,因为上面的内容更具可读性)

useList.stream()
        .mapToInt(User::getAge)
        .reduce(0, (acc, current) -> acc + current);

Or as suggested by Holger@ 或按照Holger @的建议

user.stream()
    .reduce(0, (c, user) -> c + user.getAge(), (a, b) -> a + b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 您如何从数组列表中提取项目并对其进行计数,以便根据Java中的元素及其总计数创建映射(正确)? - How do you pull items from an array list and count them in order to create a map from the element and its total count (properly) in Java? 如何获取列表中特定索引中的项目总数 <object> ? - How to get total items count in specific index of List<object>? 列表json响应中的总计数/计数项 - total / count items from list json response Java - 如何在另一个列表的列表中查找项目数 - Java - How to find count of items in a list in another list Java 8-按列表分组,排序并显示总数 - Java 8 - Group by a List, sort and display the total count of it 如何在listView中初始化商品的总计数和某个价格的总价值? - How to initialize in listView total count of items and total value of some price? Java:计算HashMap <String,ArrayList <String >>中的项目总数 - Java: count the total number of items in a HashMap<String, ArrayList<String>> 如何使用java 8在文本文件中查找单词总数、元音总数、特殊字符总数 - How to find total count of Words, total count of Vowels, total count of Special Character in a text file using java 8 如何在Java中获取员工总数? - How to get total count number of employee in Java? Java Stream API - 计算嵌套列表的项目 - Java Stream API - count items of a nested list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM