In this quick tutorial, we’ll learn ways to find the maximum/minimum element in a Java array of primitives. We’ll start with the very basic algorithms and end up with a solution using Java 8 Streams API.
It is a pretty straightforward approach to find max/min elements in a given array. We start by looking at each element to see if it’s the max/min value in our array:
public int getMaxValue(int[] numbers){ int maxValue = numbers[0]; for(int c=1;c < numbers.length;c++){ if(numbers[c] > maxValue){ maxValue = numbers[c]; } } return maxValue; } public int getMinValue(int[] numbers){ int minValue = numbers[0]; for(int c=1;c<numbers.length;c++){ if(numbers[c] < minValue){ minValue = numbers[c]; } } return minValue; }
The above solution can also be written in a recursive fashion. Let’s do it:
int getMaximumValue(int[] numbers, int size){ //last element in an array, return element if(size == 1) return numbers[0]; return Math.max(numbers[size -1], getMaximumValue(numbers, size -1)); } int getMinimumValue(int[] numbers, int size) { //last element in an array, return element if(size == 1) return numbers[0]; return Math.min(numbers[size-1], getMinimumValue(numbers, size - 1)); }
The idea here is to keep finding the max/min recursively by comparing the very last element with the minimum among the array with size one less than the original array.
We’ll be invoking these methods by passing array length as a second argument:
int max = getMaximumValue(numbers, numbers.length); int min = getMinimumValue(numbers, numbers.length);
Another simple approach to finding a max/min element in a Java array involves sorting the original array. Once the array is sorted(say in ascending order), then the first element has the minimum value whereas the last element has the maximum value:
int[] numbers={5, 4, 1, 3, 6, 2}; Arrays.sort(numbers); int max = numbers[numbers.length - 1]; int min = numbers[0];
The java.util.stream.IntStream interface provides the min/max methods which can work wonders for us. To use this approach, we’ll first have to open a stream over our array of integers:
int[] numbers={5, 4, 1, 3, 6, 2}; int max = Arrays.stream(numbers) .min() .getAsInt(); int max = Arrays.stream(numbers) .max() .getAsInt();
We have further used getAsInt() method because the methods – min()/max() in IntStream returns an OptionalInt as an output.
In this quick tutorial, we looked at four simple approaches to find the maximum/minimum element in a given Java array of primitives.
how to find one and more employee of same max age, how to find all list of employee which have max age.