-1

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.

6
  • This looks promising: Lambda expression to initialize array Commented Nov 5, 2020 at 1:19
  • You are getting only zeros because you don't write anything to your arrays. You just iterate all elements, which are default-initialized to zero, and always overwrite the local variable y by generateDouble. Commented Nov 5, 2020 at 1:22
  • @akuzminykh I wanted it to be shorter then my instructor version at university but now seems like he know what he's doing Commented Nov 5, 2020 at 1:25
  • Yes, just keep it simple and use loops in the beginning. The answer that you've accepted is btw. wrong. It addresses a right thing, but doesn't answer your question. Commented Nov 5, 2020 at 1:26
  • @akuzminykh Can you explain that further? Java Streams are not modifying their source in any way. Taken from here: 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. Commented Nov 5, 2020 at 1:34

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.