This post will discuss how to find the minimum and maximum element in an array in Java.

1. Using List

If the given array is a non-primitive array, we can use Arrays.asList() that returns a list backed by the array. Then we call the min() and max() methods of the Collections class to get minimum and maximum elements, respectively. Notice that this does not perform an actual copy on array elements.

Download  Run Code

 
For primitive arrays, we can use Java 8 Stream for converting the array to a list.

Download  Run Code

2. Using Guava Library

The Guava library has Ints, Doubles, Chars, Longs, etc., classes that offer several static utility methods pertaining to primitives that are not already found in either Integer or Arrays class. To find the minimum and maximum element, we can use the min() and max() methods of the corresponding class.

Download Code

3. Using Java 8 Stream

With the introduction of Stream with Java 8, we can convert the array into the corresponding type stream using the Arrays.stream() method. Then we can call the max() and min() method, which returns the maximum and minimum element of this stream as OptionalInt.

Download  Run Code

 
We can also get stream without using the Arrays.stream() method, as shown below. Here, the idea is to get a stream of array indices and map every index to the corresponding element in the array.

Download  Run Code

 
Finally, we can call the summaryStatistics() method on a stream of numeric values, which returns IntSummaryStatistics describing various summary data about the elements of this stream. To get the minimum and maximum element, call getMin() and getMax() methods on it.

Download  Run Code

 
This is equivalent to:

Download  Run Code

4. Write your own utility method

We can also write our own routine for finding the minimum and maximum element in the array, as demonstrated below:

Download  Run Code

5. Using Sorting

Another solution is to sort the given array in the natural order. The minimum element would then be the first element, and the maximum element is the last element of the array. This option is not recommended as the time taken by the sorting routine will not be linear, and this also modifies the original array.

Download  Run Code

That’s all about finding the minimum and maximum elements in an array in Java.