如何在java中将3D数组转换为1D数组?
我使用了以下代码:
input :double [][][]S_p = { { { 1.1, 2.1 }, { 3.2, 4.1 } },
{ { 5.2, 6.1 }, { 7.1, 8.3 } } };
int rows = S_p.length;
int columns = S_p[0].length;
int depth = S_p[0][0].length;
double [] d1 = new double[row*columns*depth];
for(int i=0;i<depth;i++) {
for(int j=0;j<rows;j++){
for(int k=0;k<columns;k++) {
for(int ii=0;ii<rows*columns*depth;ii++) {
d1 [ii] = S_p[ depth *rows *i + columns *k +j];
}
}
}
out put b[]= {1.1, 2.1, 3.2 , 4.1 ...}
但这不起作用
最佳答案
在 Java 8 中,您可以简单地执行以下操作:
double[][][] vals = {{{1.1, 2.1}, {3.2, 4.1}}, {{5.2, 6.1}, {7.1, 8.3}}};
double[] test = Arrays.stream(vals)
.flatMap(Arrays::stream)
.flatMapToDouble(Arrays::stream)
.toArray();
System.out.println(Arrays.toString(test));
输出:
[1.1, 2.1, 3.2, 4.1, 5.2, 6.1, 7.1, 8.3]
说明:
Arrays.stream(vals)
创建 Stream<double[][]>
.
.flatMap(Arrays::stream)
将其压平为Stream<double[]>
.flatMapToDouble
压平Stream<double[]>
进入DoubleStream
最后.toArray()
收集 DoubleStream
中的所有值并返回 double[]
.
关于java - 将 3D 数组展平为 1D 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38204579/