Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to find the max and min in an array

Short answer

A stream over a number array can find the maximum and minimum:

void main() {
    int[] numbers = {7, 2, 9, 4};
 
    IO.println(Arrays.stream(numbers).max().getAsInt());
    IO.println(Arrays.stream(numbers).min().getAsInt());
}

Output:

9
2

Everything at once

summaryStatistics() calculates the minimum, maximum, sum and average in one pass:

void main() {
    int[] numbers = {7, 2, 9, 4};
    IntSummaryStatistics stats = Arrays.stream(numbers).summaryStatistics();
 
    IO.println(stats.getMin() + " " + stats.getMax() + " " + stats.getAverage());
}

Output:

2 9 5.5

With a loop

The classic way: remember the first element and compare the rest with it:

void main() {
    int[] numbers = {7, 2, 9, 4};
    int max = numbers[0];
    for (int n : numbers) {
        if (n > max) {
            max = n;
        }
    }
    IO.println(max);
}

Output:

9

An array of objects

For objects, pass a comparator by the field you need:

record Product(String name, double price) {}
 
void main() {
    Product[] products = {new Product("Tea", 3.5), new Product("Cake", 12.0), new Product("Water", 1.2)};
 
    Product cheapest = Arrays.stream(products).min(Comparator.comparingDouble(Product::price)).orElseThrow();
    IO.println(cheapest.name());
}

Output:

Water

Common mistake

Starting the maximum search with zero. If all numbers are negative, the answer is wrong:

void main() {
    int[] numbers = {-5, -2, -9};
    int max = 0;
    for (int n : numbers) {
        max = Math.max(max, n);
    }
    IO.println(max);
}

Output:

0

Start with the first element of the array or with Integer.MIN_VALUE.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.