Core Java

Find Maximum/Minimum Element In Java Array

Introduction:

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.

 

Approach 1:: Linear Search

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:

Approach 2:: Recursive Approach

The above solution can also be written in a recursive fashion. Let’s do it:

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:

 

Approach 3:: Using Sorting

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:

Approach 4:: Java 8 Streams API

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:

We have further used getAsInt() method because the methods – min()/max() in IntStream returns an OptionalInt as an output.

Conclusion:

In this quick tutorial, we looked at four simple approaches to find the maximum/minimum element in a given Java array of primitives.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *