英文:
How to reduce 3d integer array to 2 dimensions?
问题
我有一个三维整数数组,我想通过沿着第三维计算最大值来将其降低为二维。
实际上,我在 Java 中正在寻找类似于 numpy.amax(array, axis=3) 的操作。我还尝试过自己实现这个功能,但是我的代码非常慢。有人知道如何在 Java 中高效地执行这个操作吗?
英文:
I have a 3d integer array and I want to reduce it to 2 dimensions by calculating the maximum along the third dimension.
I'm essentially looking for numpy.amax(array, axis=3) in java. I have also tried implementing this functionality myself, but my code is very slow. Does anyone know how to do this operation efficiently in java?
答案1
得分: 0
你可以遍历这个3D数组,其中每个元素都是一个2D数组 ⇒ 遍历2D数组,其中每个元素都是一个1D数组 ⇒ 并获取1D数组的最大值。为此,您可以使用 Stream.max(Comparator) 方法:
Integer[][][] arr3d = {
        {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}},
        {{19, 20, 21}, {22, 23, 24}, {25, 26, 27}},
        {{28, 29, 30}, {31, 32, 33}, {34, 35, 36}}
};
Integer[][] result = Arrays.stream(arr3d).map(arr2d ->
        Arrays.stream(arr2d).map(arr1d ->
                Arrays.stream(arr1d)
                        .max(Comparator.comparingInt(Integer::intValue))
                        .orElse(null))
                .toArray(Integer[]::new))
        .toArray(Integer[][]::new);
Arrays.stream(result).map(Arrays::toString).forEach(System.out::println);
// [12, 15, 18]
// [21, 24, 27]
// [30, 33, 36]
或者,如果您有一个基本类型 int[][][] 的3D数组,您可以使用 IntStream.max() 方法:
int[][] result = Arrays.stream(arr3d).map(arr2d ->
        Arrays.stream(arr2d).mapToInt(arr1d ->
                Arrays.stream(arr1d)
                        .max()
                        .orElse(0))
                .toArray())
        .toArray(int[][]::new);
<sup>另请参阅:使用预定义的Java方法查找数组中的最大数</sup>
英文:
You can iterate over this 3d array, where each element is a 2d array ⇒ iterate over 2d arrays, where each element is a 1d array ⇒ and get maximun value of 1d array. For this purpose you can use Stream.max(Comparator) method:
Integer[][][] arr3d = {
        {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}},
        {{19, 20, 21}, {22, 23, 24}, {25, 26, 27}},
        {{28, 29, 30}, {31, 32, 33}, {34, 35, 36}}};
Integer[][] result = Arrays.stream(arr3d).map(arr2d ->
        Arrays.stream(arr2d).map(arr1d ->
                Arrays.stream(arr1d)
                        .max(Comparator.comparingInt(Integer::intValue))
                        .orElse(null))
                .toArray(Integer[]::new))
        .toArray(Integer[][]::new);
Arrays.stream(result).map(Arrays::toString).forEach(System.out::println);
// [12, 15, 18]
// [21, 24, 27]
// [30, 33, 36]
Or if you have a 3d array of primitives int[][][], you can use IntStream.max() method:
int[][] result = Arrays.stream(arr3d).map(arr2d ->
        Arrays.stream(arr2d).mapToInt(arr1d ->
                Arrays.stream(arr1d)
                        .max()
                        .orElse(0))
                .toArray())
        .toArray(int[][]::new);
<sup>See also: Finding the largest number in an array using predefined java methods</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论