Reputation: 35
is it possible to copy the data from multi[][] to single[]?!?
double multi[][] = { {1.0, 2.0}, {2.11, 204.00, 11.00, 34.00},{66.5,43.3,189.6}};
to
double single [] = {1.0, 2.0, 2.11, 204.00, 11.0, 66.5,43.3,189.6}
Upvotes: 0
Views: 3005
Reputation: 328913
With Java 8 you can write:
double[] single = Arrays.stream(multi) //Creates a Stream<double[]>
.flatMapToDouble(Arrays::stream) //merges the arrays into a DoubleStream
.toArray(); //collects everything into a double[] array
Upvotes: 4
Reputation: 234857
It's entirely possible. Per @assylias's answer, Java 8 has a very nice solution. If you're not using Java 8, you'll have to do some work by hand. Since the multi
elements are different length, The most efficient thing to do would be to use two passes: the first to count how many elements you need in the result and the second to actually copy the elements once you've allocated the array:
int n = 0;
for (int[] elt : multi) {
n += elt.length;
}
double[] single = new double[n];
n = 0;
for (int[] elt : multi) {
System.arraycopy(elt, 0, single, n, elt.length);
n += elt.length;
}
If it is at all possible that an element of multi
is null
, you'd want to add an appropriate check inside each of the loops.
Upvotes: 2
Reputation: 9900
if you want a logical way..first you have to find the length of multy array content .and then make single [] with that length and add values
double multy[][] = { {1.0, 2.0}, {2.11, 204.00, 11.00, 34.00},{66.5,43.3,189.6}};
int y=0;
for(int x=0;x<multy.length,x++){
for(int i=0;i<multy[x].length,i++){
y++;
}
}
double single [] =new double[y];
y=0;
for(int x=0;x<multy.length,x++){
for(int i=0;i<multy[x].length,i++){
y++;
single[y]==multy[x][i];
}
}
Upvotes: 1
Reputation: 190
According to: https://stackoverflow.com/questions/20686499/java-how-to-convert-a-multidimensional-array-to-single-array-easily
ArrayUtils.addAll(array1,array2)
Upvotes: 0