How to Use Collections.min in Java: Simple Guide with Examples
Use
Collections.min(Collection<T> coll) to find the smallest element in a collection in Java. It requires the elements to be Comparable or you can provide a Comparator with Collections.min(Collection<T> coll, Comparator<? super T> comp).Syntax
The Collections.min method has two main forms:
Collections.min(Collection<T> coll): Finds the minimum element using natural ordering. Elements must implementComparable.Collections.min(Collection<T> coll, Comparator<? super T> comp): Finds the minimum element using a customComparator.
Here, T is the type of elements in the collection.
java
T minElement = Collections.min(coll); T minElementWithComparator = Collections.min(coll, comp);
Example
This example shows how to find the smallest number in a list of integers using Collections.min. It also shows how to find the minimum string by length using a custom comparator.
java
import java.util.*; public class MinExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 3, 9, 1, 7); int minNumber = Collections.min(numbers); System.out.println("Minimum number: " + minNumber); List<String> words = Arrays.asList("apple", "banana", "pear", "kiwi"); String shortestWord = Collections.min(words, Comparator.comparingInt(String::length)); System.out.println("Shortest word: " + shortestWord); } }
Output
Minimum number: 1
Shortest word: pear
Common Pitfalls
Common mistakes when using Collections.min include:
- Passing an empty collection causes
NoSuchElementException. - Using elements that do not implement
Comparablewithout providing aComparatorcausesClassCastException. - Modifying the collection while finding the minimum can cause unexpected behavior.
Always check the collection is not empty and elements are comparable or provide a comparator.
java
import java.util.*; public class PitfallExample { public static void main(String[] args) { List<Object> items = Arrays.asList(new Object(), new Object()); // This will throw ClassCastException because Object is not Comparable // Object minItem = Collections.min(items); List<Integer> emptyList = new ArrayList<>(); // This will throw NoSuchElementException because list is empty // int minEmpty = Collections.min(emptyList); } }
Quick Reference
Collections.min Cheat Sheet:
Collections.min(coll): Finds smallest element by natural order.Collections.min(coll, comparator): Finds smallest element by custom order.- Throws
NoSuchElementExceptionif collection is empty. - Elements must implement
Comparableor provide aComparator.
Key Takeaways
Use Collections.min to find the smallest element in a collection easily.
Elements must be Comparable or you must provide a Comparator.
Avoid empty collections to prevent NoSuchElementException.
Use the overload with Comparator to customize the comparison logic.
Collections.min works with any Collection type like List, Set, etc.