Collections.min()
Finds the smallest element of a collection.
Available since: Java 1.2
Syntax
static <T extends Comparable<? super T>> T min(Collection<? extends T> coll)
static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp)Parameters
| Parameter | Type | Description |
|---|---|---|
| coll | Collection<? extends T> | A non-empty collection. |
| comp | Comparator<? super T> | Optional comparison rule. |
Return value
TThe smallest element.
Examples
The smallest number and the cheapest product:
record Product(String name, double price) {}
void main() {
IO.println(Collections.min(Set.of(30, 12, 45)));
var items = List.of(new Product("pen", 1.5), new Product("book", 12), new Product("clip", 0.2));
IO.println(Collections.min(items, Comparator.comparingDouble(Product::price)).name());
}Output:
12
clipNotes
It works with any collection, not only lists. An empty collection throws NoSuchElementException.
See also
- Collections.max() — Finds the largest element of a collection.
- Stream.min() — Finds the smallest element of a stream.
Related recipes
In the tutorial
- Collection helper methods — The Collections class and useful Java methods: max, min, frequency, reverse, shuffle, nCopies, unmodifiable copies and views, Arrays.asList.