将列表<double [] []>折叠为double [] []

时间:2015-05-05 21:56:11

标签: java arrays list

我有一个List<double[][]>

类型的变量

列表中的内容示例如下(每个新行都是列表元素):

{ {1.0,0.0,0.0}, {0.0,0.0,0.0} }
{ {0.0,0.0,0.0}, {1.0,0.0,0.0}, {0.0,1.0,0.0} }

我需要实现的结果是double[][],其中包含列表中的所有元素(使用与上面相同的值):

{ {1.0,0.0,0.0}, {0.0,0.0,0.0}, {0.0,0.0,0.0}, {1.0,0.0,0.0}, {0.0,1.0,0.0} }

最内层数组的大小始终相同。但是,外部阵列的大小不同。

我真的很感激这方面的一些帮助,我似乎认为解决方案很简单,但我无法想出来!

2 个答案:

答案 0 :(得分:8)

这就是Streaming API的flatMap所针对的:

List<double[][]> list = Arrays.asList(
        new double[][]{{1.0, 0.0, 0.0}, {0.0, 0.0, 0.0}},
        new double[][]{{0.0, 0.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}});

double[][] result = list.stream()
        .flatMap(Arrays::stream)
        .toArray(double[][]::new);

制作{ {1.0,0.0,0.0}, {0.0,0.0,0.0}, {0.0,0.0,0.0}, {1.0,0.0,0.0}, {0.0,1.0,0.0} }

答案 1 :(得分:4)

List<double[][]> list;

//calculate the length of the array (sum of the length of all double[][]s in the list)
int resultLen = 0;
for(double[][] d : list)
    resultLen += d.length;

double[][] result = new double[resultLen][];

//copy all double[]s that are in the list (wrapped into double[][]s)
//into the new double[][]
int index = 0;
for(double[][] d : list)
    for(double[] a : d)
        result[index++] = a;

return result;