Home > Blockchain >  How to transform a 2D array to a list with summation of all the elements
How to transform a 2D array to a list with summation of all the elements

Time:08-22

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 retrive the summation of all the lists? Using Java IntStream method? 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>

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

CodePudding user response:

You mean like this?

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

CodePudding user response:

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

CodePudding user response:

There is no IntStream, but it works:

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