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.