In Java, if a 2D array is given as input we can find the Min number using the for loop or Java 8 IntSummaryStatistics class.
We have taken a 2D multidimensional array as input. Our goal is to traverse the two dimensional array and find the minimum number from it.
In the previous example, we saw a program to find the maximum integer. The code given here is written in a similar fashion.
FindMinNumber.java
package com.digitizedpost.array;
public class FindMinNumber {
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("Min Number : "+ getMinNumber(input));
}
public static int getMinNumber(int[][] array) {
int minNumber = array[0][0];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] < minNumber) {
minNumber = array[i][j];
}
}
}
return minNumber;
}
}
array[0][0] can be also replaced with Integer.MAX_VALUE.
int minNumber = Integer.MAX_VALUE;
In earlier versions of Java, we can use for loop to traverse the 2D array using for loop. In Java 8, we are going to use IntSummaryStatistics class to get the min statistics.
Output
The output will be the minimum integer i.e., -10
Min Number : -10
Java 8 Find Minimum Integer in a 2d Array
package com.digitizedpost.array;
import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class FindMinNumber {
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("Min Number : "+ getMinNumber(input));
}
public static int getMinNumber(int[][] array) {
IntSummaryStatistics stats = Stream.of(array)
.flatMapToInt(IntStream::of)
.summaryStatistics();
return stats.getMin();
}
}
In the next topic, we will see how to find a duplicate number in a multidimensional array.