For a given 2D Array we can find the max number. Here we are going to explain the examples with java 8 and earlier versions.
In the below code a two dimensional array of integers is given as input. From the given input, using for loop the maximum integer is printed in the console.
FindMaxNumber.java
package com.digitizedpost.array;
public class FindMaxNumber {
public static void main(String[] args) {
int[][] input = {
{1, 2, 7},
{1, 15, 6, 1, 50},
{3, 9, 0, -2, 3},
{5, 4, 3, 3, 0, -10}
};
System.out.println("Max Number : " + getMaxNumber(input));
}
public static int getMaxNumber(int[][] array) {
int maxNumber = array[0][0];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] > maxNumber) {
maxNumber = array[i][j];
}
}
}
return maxNumber;
}
}
Output
The output of the program will be 50 which is the largest number in the 2d array.
Max Number : 50
The array is initialized with zero. We can also replace the initialization with the Integer.MIN_VALUE
int maxNumber = Integer.MIN_VALUE;
Java 8 Find Maximum number in Two Dimensional Array
In Java 8, the code can be rewritten as
package com.digitizedpost.array;
import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class FindMaxNumber {
public static void main(String[] args) {
//2d array input here
System.out.println("Max Number : " + getMaxNumber(input));
}
public static int getMaxNumber(int[][] array) {
IntSummaryStatistics stats = Stream.of(array)
.flatMapToInt(IntStream::of)
.summaryStatistics();
return stats.getMax();
}
}
Using flatMapToInt we are getting a flattened integer array and we have got the Max statistics from the summaryStatistics terminal operation.
Given a M x N (say 4 x 4) matrix of integers like below, you can use the above same code. Just replace the input.
//matrix 4x4
int[4][4] input = {
{1, 2, 7, 21},
{1, 15, 6, 1},
{3, 9, 0, -2},
{5, 4, 3, 3, 0}
};
In this example, we have found the maximum element in a given Matrix ( 2d array). In a similar approach, we can also find the min statistics which will be discussed in the upcoming post.