首页 > 解决方案 > 如何将嵌套列表转换为二维数组

问题描述

我需要将嵌套的 Double 列表转换为 double[][]。我尝试使用下面的代码,但问题是如何转换为原始双精度。任何帮助将非常感激。

double[][] matrix = new double[listReturns.size()][];
    int i = 0;
    for (List<Double> nestedList : listReturns) {
        matrix[i++] = nestedList.toArray(new Double[nestedList.size()]);
    }

标签: java

解决方案


您可以使用流:

double[][] mat =
    listReturns.stream() // Stream<List<Double>>
               .map(list -> list.stream() 
                                .mapToDouble(Double::doubleValue)
                                .toArray()) // map each inner List<Double> to a double[]
               .toArray(double[][]::new); // convert Stream<double[]> to a double[][]

推荐阅读