如何将二维数组转换为包含所有元素总和的列表

问题描述 投票:0回答:4

假设存在三个固定大小的整数列表,并且所有列表都存储在另一个列表中

List<List<Integer> a = <<1,2,3>, <1,2,3>, <1,2,3>>

是否可以检索所有列表的总和?使用Java IntStream方法?预期结果如下:

<<a1,b1,c1>, <a2,b2,c2>, <a3,b3,c3>>

//Would Produce Result Of
<a1+a2+a3, b1+b2+b3, c1+c2+c3>

< 1+1+1, 2+2+2 , 3+3+3 >
<3,6,9>

正在考虑首先将整个事物平面映射为:

<1,2,3,1,2,3,1,2,3>

我的代码尝试如下:

List<Integer> newList = new ArrayList<>;
Arrays.setAll(newList .toArray(), in->{
        IntStream.range(1,b).forEach(y->
                newList.set(a, a.get(0) + a.get(3*y))
        );
    });
java arrays list stream
4个回答
1
投票

流解决方案可能看起来像这样

List<List<Integer>> list = List.of(List.of(1,2,3), List.of(1,2,3), List.of(1,2,3));

List<Integer> result = IntStream.range(0, list.get(0).size())
    .mapToObj(i -> list.stream().mapToInt(l -> l.get(i)).sum())
    .toList(); // or before Java 16 .collect(Collectors.toList())
System.out.println(result);

更新:或者,如果您更喜欢迭代方式

List<List<Integer>> list = List.of(List.of(1,2,3), List.of(1,2,3), List.of(1,2,3));

List<Integer> result = new ArrayList<>();
for (int i = 0, n = list.get(0).size(); i < n; i++) {
    int sum = 0;
    for (List<Integer> innerList : list) {
        sum += innerList.get(i);
    }
    result.add(sum);
}

System.out.println(result);

0
投票

你的意思是这样吗?

List<Integer> output = new ArrayList<>();
for(List<Integer> innerList : a)  { // Where a = new List<List<Integer>>
    int sum = 0;
    for(int i : innerList) {
        sum += i;
    }
    output.add(sum);
    sum = 0;
}
int[] resultArray = output.toArray();

0
投票

没有 IntStream,但它可以工作:

    List<List<Integer>> lists = List.of(List.of(1,2,3), List.of(4,5,6), List.of(7,8,9));

    // list with sum of ints = <6,15,24>
    List<Integer> sums = lists.stream()
        .map(list -> list.stream().reduce(0, (a, b) -> a + b))
        .collect(Collectors.toList());

    // or total sum of ints = 44
    Integer total = lists.stream()
        .flatMap(List::stream)
        .reduce(0, (a, b) -> a + b);

0
投票
IntStream.range(0, a.getFirst().size())
        .mapToObj(i -> a.stream().mapToInt(l -> l.get(i)).sum())
        .toList();

这首先创建一个从 0 到

n
(不包括)的列表索引 IntStream,其中 n 是第一个子列表的大小。然后,它将每个索引元素 (i) 映射到每个子列表的第 i 元素的总和。最后,它将这个
Stream<Integer>
总和转换为
List<Integer>

© www.soinside.com 2019 - 2024. All rights reserved.