简体   繁体   English

将多数组转换成单数组(java)

[英]convert multi array into single array(java)

is it possible to copy the data from multi[][] to single[]?!? 是否可以将数据从multi [] []复制到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}

With Java 8 you can write: 使用Java 8,您可以编写:

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

It's entirely possible. 这是完全可能的。 Per @assylias's answer , Java 8 has a very nice solution. 根据@assylias的回答 ,Java 8有一个非常好的解决方案。 If you're not using Java 8, you'll have to do some work by hand. 如果您不使用Java 8,则必须手动完成一些工作。 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: 由于multi元素的长度不同,因此最有效的方法是使用两次遍历:第一次遍历结果中需要多少个元素,第二遍分配数组后实际复制元素:

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. 如果multi元素完全有可能为null ,则需要在每个循环中添加一个适当的检查。

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];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM