Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
2

By 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:

Cake

With 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
0

Common 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.NoSuchElementException

Check isEmpty() beforehand or use a stream with orElse().

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.