Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
collCollection<? extends T>A non-empty collection.
compComparator<? 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
clip

Notes

It works with any collection, not only lists. An empty collection throws NoSuchElementException.

See also

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.

Thanks for reading!

Donate to the site — we work hard for you.