简体   繁体   中英

How to fill 2 dimensional array using Lambda in Java

I'am trying to create simple 2 dimensional array of double . Using for loop it's not a big deal to make it like:

static public double[][] genMatrix(int n) {
    double mat[][]=new double[n][n];
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            mat[i][j]=generateDouble();
    return mat;
}

I'd like to do it smoother with a lambda expression and forEach but I'm getting an array full of zeros. Why?

private static double[][] genSquareMatrix(int matrixDimension) {
    double matrix[][] = new double[matrixDimension][matrixDimension];
    Arrays.stream(matrix).forEach(x->Arrays.stream(x).forEach(y-> y = generateDouble()));
    return matrix;
}

By the way, when I use a lambda to print that array there is no problem.

Regarding to documentation

Functional in nature. An operation on a stream produces a result, but does not modify its source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection.

It returns a DoubleStream , which supports

sequential and parallel aggregate operations

This is why it not works.

Edit: The first section was incorrect. Replaced it by a more correct version

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM