Collections.min and max with Custom Comparators
What you'll learn: How to find the smallest and largest elements in a collection without writing loops, using either natural ordering or custom comparison logic.
The Core Idea
When you have a collection and need to find the "best" or "worst" element according to some criteria, Collections.min() and Collections.max() do the heavy lifting for you. They scan through the entire collection once and return the extreme value—no manual iteration required.
Think of it like a judge at a competition: you can judge contestants by their natural scoring system (like age or alphabetical order), or you can provide your own judging criteria (tallest, fastest, most creative).
Natural Ordering
For types that implement Comparable (like Integer, String, LocalDate), you can use the single-argument version:
List<Integer> numbers = List.of(42, 8, 15, 23, 4);
int smallest = Collections.min(numbers); // 4
int largest = Collections.max(numbers); // 42
List<String> names = List.of("Zoe", "Alice", "Bob");
String first = Collections.min(names); // "Alice"
String last = Collections.max(names); // "Zoe"
Custom Comparators
When you need different comparison logic, pass a Comparator as the second argument:
List<String> words = List.of("apple", "fig", "banana");
// Find shortest word
String shortest = Collections.min(words, Comparator.comparingInt(String::length)); // "fig"
// Find longest word
String longest = Collections.max(words, Comparator.comparingInt(String::length)); // "banana"
Both methods throw NoSuchElementException if the collection is empty.
Key Takeaway: Use Collections.min() and Collections.max() with optional custom comparators to find extreme values in any collection without manual loops—they work with natural ordering or your own comparison rules.