0

I need to convert a double[][] (2D array of primitives type) into Double[][] (2D array of Double wrapper class).

Is there a better solution other than the one that I already have?

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

}

I know I can convert the toObject method into use lambda which would be a good approach. Any comments and/or suggestions from the community?

Thanks in advance.

Flavio Oliva
  • 401
  • 4
  • 15
  • Probably fine. What do you mean by "better"? There are many possible metrics. What specific problem are you having with this solution that you want to fix? – Mad Physicist Mar 10 '20 at 15:50
  • I guess performance would be the most important metric. Memory usage as well would be a good to keep as low as possible. – Flavio Oliva Mar 10 '20 at 18:27

1 Answers1

1

You can do it also as follows:

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

Output:

[[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]]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110