-1

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?

0

1 Answer 1

0

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

See also: Finding the largest number in an array using predefined java methods

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.