【问题标题】:converting double[][] to Double[][] [duplicate]将 double[][] 转换为 Double[][] [重复]
【发布时间】:2020-06-22 13:28:22
【问题描述】:

我需要将 double[][](原始类型的二维数组)转换为 Double[][](Double 包装类的二维数组)。

除了我已有的解决方案之外,还有更好的解决方案吗?

import java.util.stream.IntStream;

public class DoubleUtils {

    public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];

    static final double[][] testArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    public static Double[][] toObject(double[][] array) {
        return IntStream.range(0, array.length).mapToObj(x -> toObject(array[x])).toArray(Double[][]::new);
    }

    public static void main(String[] args) {
        Double[][] returnArray = toObject(testArray);
        System.out.println(testArray);
        System.out.println(returnArray);
    }

    /**
     * 
     * CODE FROM APACHE COMMON LANG 3
     * <p>
     * Converts an array of primitive doubles to objects.
     *
     * <p>
     * This method returns {@code null} for a {@code null} input array.
     *
     * @param array a {@code double} array
     * @return a {@code Double} array, {@code null} if null array input
     */
    public static Double[] toObject(final double[] array) {
        if (array == null) {
            return null;
        } else if (array.length == 0) {
            return EMPTY_DOUBLE_OBJECT_ARRAY;
        }
        final Double[] result = new Double[array.length];
        for (int i = 0; i < array.length; i++) {
            result[i] = Double.valueOf(array[i]);
        }
        return result;
    }

}

我知道我可以将toObject 方法转换为使用lambda,这将是一个好方法。来自社区的任何 cmets 和/或建议?

提前致谢。

【问题讨论】:

  • 可能没问题。 “更好”是什么意思?有许多可能的指标。您希望解决此解决方案的哪些具体问题?
  • 我猜性能将是最重要的指标。尽可能降低内存使用量也是一个不错的选择。

标签: java


【解决方案1】:

你也可以这样做:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        double[][] testArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        Double[][] returnArray = Arrays.stream(testArray).map(d -> Arrays.stream(d).boxed().toArray(Double[]::new))
                .toArray(Double[][]::new);
        System.out.println(Arrays.deepToString(testArray));
        System.out.println(Arrays.deepToString(returnArray));
    }
}

输出:

[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 1970-01-01
    • 2018-09-23
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2023-04-01
    • 2016-10-10
    相关资源
    最近更新 更多