Home > Net >  Fast conversion of single dimension array to two dimensional 'column' array
Fast conversion of single dimension array to two dimensional 'column' array

Time:08-07

Are there any built-in functions (or fast implementations) in Java to convert a single-dimension array of size [n] to a two-dimensional array of size [n][1]?

For example:

double[] x = new double[]{1, 2, 3};
double[][] x2D = new double[][]{{1}, {2}, {3}};

CodePudding user response:

If you're looking for a built-in function to convert a single dimension array to a two-dimensional one, sadly there isn't one.

However, as it has been pointed out in the comments, you could use streams to reach a fair compact way to initialize your two-dimensional array from a single-dimension one. Basically, you could define your matrix's dimension from the array's length and then rely on a stream to copy the array's elements within the two-dimensional array.

double[] x = new double[]{1, 2, 3};
double[][] x2D = new double[x.length][1];
IntStream.range(0, x.length).forEach(i -> x2D[i][0] = x[i]);

Or in a more concise writing, you could immediately initialize your two-dimensional array with a stream where each element is mapped to a double[] and then collect each one of them into a further array.

double[] x = new double[]{1, 2, 3};
double[][] mat = Arrays.stream(x).mapToObj(i -> new double[]{i}).toArray(double[][]::new);

CodePudding user response:

Arrays.setAll method can be used:

double[] x     = {1, 2, 3};
double[][] x2D = new double[x.length][];

Arrays.setAll(x2D, i -> new double[]{x[i]});
  • Related