Search code examples
javaarrayslistsumjava-stream

How to transform a 2D list to a list with summation of all the elements


Given that there are three lists of Integers with all fixed size and all the lists are stored in another list:

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

Is it possible to retrieve the summation of all the lists using IntStream? Expected result as below:

<<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>

Ias thinking to first flatMap the entire thing to become something like:

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

My attempt of code is as below:

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))
        );
    });

Solution

  • A stream solution could look like

    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);
    

    Update: or, if you prefer the iterative way

    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);