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
2Everything 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.5With 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:
9An 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:
WaterCommon 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:
0Start with the first element of the array or with Integer.MIN_VALUE.
Functions used in this recipe
- Arrays.stream() — Creates a stream from an array — for sums, filters and transformations.
- IntStream.average() — Computes the arithmetic mean of the numbers in a stream.
- Collections.max() — Finds the largest element of a collection.
- Math.max() — Returns the larger of two numbers.