Arrays.fill with multidimensional array in Java

后端 未结 13 1834
心在旅途
心在旅途 2020-11-27 18:49

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);

13条回答
  •  醉酒成梦
    2020-11-27 19:23

    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][]);
    

提交回复
热议问题