首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ArrayList<ArrayList<Integer>>之和?

ArrayList<ArrayList<Integer>>之和?
EN

Stack Overflow用户
提问于 2017-05-04 17:04:33
回答 6查看 1.1K关注 0票数 0

有没有办法在inputList中找到列表中所有元素的和?

这是我尝试过的,但这只适用于我假设的常规ArrayList整数。

代码语言:javascript
复制
static int add(ArrayList<ArrayList<Integer>> inputList) {
    int a = (int) inputList;
    int sum = 0;

    for(int d : a)
        sum = sum + d;

    return sum;
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2017-05-04 17:09:45

不能将ArrayList转换为整数基元类型,因此应该删除该行。出于同样的原因,您不能使用增强的For -循环,因为参数是整数的ArrayList of ArrayLists。

代码语言:javascript
复制
static int add(ArrayList<ArrayList<Integer>> inputList) {
    int sum = 0;
    for(ArrayList<Integer> nestedList : inputList) {
        for (int n : nestedList) sum += n;
    }

    return sum;
}
票数 4
EN

Stack Overflow用户

发布于 2017-05-04 17:11:12

一种方法是使用嵌套的foreach循环对外部列表和内部列表进行迭代,然后简单地将所有元素添加到一起。

代码语言:javascript
复制
static int add(ArrayList<ArrayList<Integer>> inputList) {
       int sum = 0;
       for (ArrayList<Integer> list : inputList) {
           for (int number : list) {
                sum += number;
           }
       } 
       return sum;
}
票数 3
EN

Stack Overflow用户

发布于 2017-05-04 17:12:12

您可以使用Java8流查找和,如下面的代码所示,只需一行(请遵循注释):

代码语言:javascript
复制
int sum = inputList.stream().//get the stream for the outer list
           flatMapToInt(list -> list.stream().
            mapToInt(value -> value)).//flatten the inner list
            sum();//get the sum
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43788868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档