Learn to **find the smallest and the largest item** in an array in Java. We will discuss different approaches from simple iterations to the Stream APIs.

In the given examples, we are taking an array of int values. We can apply all the given solutions to an array of objects or custom classes as well. In the case of custom objects, we only need to override the *equals()* method and provide the correct logic to compare two instances.

`int[] items = { 10, 0, 30, 2, 7, 5, 90, 76, 100, 45, 55 }; // Min = 0, Max = 100`

## 1. Find Max/Min using Stream API

Java streams provide a lot of useful classes and methods for performing aggregate operations. Let’s discuss a few of them.

### 1.1. *Stream.max()* and *Stream.min()*

The `Stream`

interface provides two methods `max()`

and `min()`

that return the largest and the smallest item from the underlying stream.

Both methods can take a custom `Comparator`

instance if we want a custom comparison logic between the items.

For primitives, we have `IntStream`

, `LongStream`

and `DoubleStream`

to support *sequential and parallel aggregate operations* on the stream items. We can use the `java.util.Arrays.stream()`

method to **convert the array to Stream** and then perform any kind of operation on it.

```
int max = Arrays.stream(items)
.max()
.getAsInt(); // 100
int min = Arrays.stream(items)
.min()
.getAsInt(); // 0
```

### 1.2. IntStream.summaryStatistics()

In the above example, we find the array’s max and min items in two separate steps. We are creating the stream two times and operating on it two times. This is useful when we only have to find either the maximum item or the minimum item.

If we have to find the max and min item both then **getting the max and min item from the array in a single iteration** makes complete sense. We can do it using the `IntSummaryStatistics`

instance. A similar instance is available for *LongStream* and *DoubleStream* as well.

```
IntSummaryStatistics stats = Arrays.stream(items).summaryStatistics();
stats.getMax(); //100
stats.getMin(); //0
```

## 2. *Collections.min()* and *Collections.max()*

The `Collections`

class provides the aggregate operations for items in a collection such as *List*. We can convert an array into a *List* and use these APIs to find the max and min items.

In the given example, **we are converting the int[] to Integer[]**. If you have an Object[] already then you can directly pass the array to `Arrays.asList()`

API.

```
Integer min = Collections.min(Arrays.asList(ArrayUtils.toObject(items)));
Integer max = Collections.max(Arrays.asList(ArrayUtils.toObject(items)));
```

## 3. Sorting the Array

Sorting the array is also a good approach for small arrays. **For large arrays, sorting may prove a performance issue** so choose wisely.

In a sorted array, the min and max items will be at the start and the end of the array.

```
Arrays.sort(items);
max = items[items.length - 1]; //100
min = items[0]; //0
```

## 4. Iterating the Array

This is the most basic version of the solution. The pseudo-code is :

Initialize the max and min with first item in the array Iterate the array from second position (index 1) Compare the ith item with max and min if current item is greater than max set max = current item elseif current item is lower than min set min = current item

After the loop finishes, the `max`

and `min`

variable will be referencing the largest and the smallest item in the array.

```
max = items[0];
min = items[0];
for (int i = 1; i < items.length; i++) {
if (items[i] > max) {
max = items[i];
}
else if (items[i] < min) {
min = items[i];
}
}
System.out.println(max); //100
System.out.println(min); //0
```

## 5. Recursion

Recursion gives better performance for a big-size unsorted array. Note that we are writing the recursive call for max and min items, separately. If we need to find both items in a single invocation, we will need to change the program as per demand.

This solution is basically **Divide and Conquer** algorithm where we only handle the current index and the result of the rest (the recursive call) and merge them together for the final output.

For getting the maximum of items, at each item, we return the larger of the current items in comparison and all of the items with a greater index. A similar approach is for finding the minimum item.

```
min = getMax(items, 0, items[0]); //0
min = getMin(items, 0, items[0]); //100
public static int getMax(final int[] numbers, final int a, final int n) {
return a >= numbers.length ? n
: Math.max(n, getMax(numbers, a + 1, numbers[a] > n ? numbers[a] : n));
}
private static int getMin(final int[] numbers, final int a, final int n) {
return a == numbers.length ? n
: Math.min(n, getMin(numbers, a + 1, numbers[a] < n ? numbers[a] : n));
}
```

## 6. Conclusion

In this short Java tutorial, we learned the different ways to find the maximum and the minimum element from an Array in Java. We learned to use the Stream API, Collections API, simple iterations, and advanced techniques such as recursion.

For smaller arrays, we should prefer the code readability and use the Stream or Collection APIs. For large arrays, where we will get noticeable performance improvements, using recursion can be considered.

Happy Learning !!

## Leave a Reply