我需要将double [] [](原始类型的2D数组)转换为Double [] [](Double包装器类的2D数组)。
除了我已经拥有的解决方案之外,还有其他更好的解决方案吗?
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
,这将是一个很好的方法。社区有什么意见和/或建议吗?
提前致谢。
您也可以按照以下步骤进行操作:
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]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句