How can I fill a multidimensional array in Java without using a loop? I\'ve tried:
double[][] arr = new double[20][4];
Arrays.fill(arr, 0);
Using Java 8, you can declare and initialize a two-dimensional array without using a (explicit) loop as follows:
int x = 20; // first dimension
int y = 4; // second dimension
double[][] a = IntStream.range(0, x)
.mapToObj(i -> new double[y])
.toArray(i -> new double[x][]);
This will initialize the arrays with default values (0.0 in the case of double).
In case you want to explicitly define the fill value to be used, You can add in a DoubleStream:
int x = 20; // first dimension
int y = 4; // second dimension
double v = 5.0; // fill value
double[][] a = IntStream
.range(0, x)
.mapToObj(i -> DoubleStream.generate(() -> v).limit(y).toArray())
.toArray(i -> new double[x][]);