There is a matrix:

List<ArrayList<Double>> matr; 

it is required to find the mean value in the matrix, without streams I do it like this:

  public Double averageMatr() { Double sum=0.0; for (ArrayList<Double> list : matr) { for (Double item : list) { sum+=item; } } return sum/matr.size()*countColumn; } 

Tell me how can this cycle be recorded in a stream?

Tried to do this:

 public Double averageMatr() { Double sum=0.0; for (ArrayList<Double> list : matr) { sum+= list.stream().mapToDouble(Double::doubleValue).average().getAsDouble(); } return sum/matr.size(); } 

But this is the wrong result. the average value is found from the rows, and the average value is then taken from the average values. That is wrong.

    1 answer 1

    This is done very simply using the Stream.flatMap method:

     matr.stream().flatMap(Collection::stream).mapToDouble(d -> d).average() 
    • thank you very much :) but how does flatMap work? - Sanaev
    • @ Sanaev flatMap essentially makes one flat stream from a stream of streams. - ZhekaKozlov
    • cool. what I was looking for. - Sanaev