How to find the max and min in a list
Short answer
Collections.max() and Collections.min() find the largest and smallest elements:
void main() {
var numbers = List.of(7, 2, 9, 4);
IO.println(Collections.max(numbers));
IO.println(Collections.min(numbers));
}Output:
9
2By an object field
Pass a comparator by the field you need:
record Product(String name, double price) {}
void main() {
var products = List.of(new Product("Tea", 3.5), new Product("Cake", 12.0), new Product("Water", 1.2));
var expensive = Collections.max(products, Comparator.comparingDouble(Product::price));
IO.println(expensive.name());
}Output:
CakeWith a stream
Stream.max() returns an Optional — it is safe for an empty list:
void main() {
List<Integer> empty = List.of();
IO.println(empty.stream().max(Integer::compare));
IO.println(empty.stream().max(Integer::compare).orElse(0));
}Output:
Optional.empty
0Common mistake
Calling Collections.max() on an empty list:
void main() {
List<Integer> empty = new ArrayList<>();
IO.println(Collections.max(empty));
}Output:
Exception in thread "main" java.util.NoSuchElementExceptionCheck isEmpty() beforehand or use a stream with orElse().
Functions used in this recipe
- Collections.max() — Finds the largest element of a collection.
- Collections.min() — Finds the smallest element of a collection.
- Stream.max() — Finds the largest element of a stream.
- Comparator.comparing() — Creates a comparator that compares objects by one key.