Home > OS >  Vertical sum using java stream api
Vertical sum using java stream api

Time:08-04

Imagine that I have a matrix of integer elements List<List<BigDecimal>>:

-------------
| 1 | 2 | 3 |
-------------
| 2 | 3 | 4 |
-------------
| 3 | 4 | 5 |
-------------
| 4 | 5 | 6 |
-------------

I want to vertically sum the elements of a matrix and get a List<BigDecimal>
[10, 14, 18]

I suppose first I have to transpose the matrix and then it's easy to get the sum of the elements. But how to perfectly transpose a matrix using stream api??

CodePudding user response:

One way to transform the 2D list is to map to an object and by collecting that list we can find the transpose of the 2D list as below:

List<List<BigDecimal>> result = IntStream.range(0, list.get(0).size())
                        .mapToObj(i -> list.stream().map(l -> l.get(i)).collect(Collectors.toList()))
                        .collect(Collectors.toList());

And Without transposing, you can directly find the sum of the list using reduce function below:

List<BigDecimal> result = IntStream.range(0, list.get(0).size())
                        .mapToObj(i -> list.stream().map(l -> l.get(i)).reduce(BigDecimal.ZERO, BigDecimal::add))
                        .collect(Collectors.toList());

CodePudding user response:

DISCLAIMER: This isn't the efficient way with streams or something fancy that you could do in just a couple lines, but it is a simple easy-to-follow way. Why not just do something simple like this? Iterate over the list length and sum that column via the index:

List<List<BigDecimal>> matrix = <<your matrix here>>
List<BigDecimal> columnSum= new List<BigDecimal>;
// For each column
for(int i = 0; i < matrix.get(0).size()-1; i  ){
      int sum = 0;
      for(List<BigDecimal> row : matrix){
            sum  = row.get(i);
      }
      columnSum.add(BigDecimal(sum));
}
  • Related