Java Collections min() Method
Example
Find the smallest number in a list:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
System.out.println(Collections.min(myNumbers));
}
}
Definition and Usage
The min() method returns the smallest item in a collection. It uses the natural order: numbers from small to large, and strings alphabetically.
You can also give a Comparator (an object that decides the order of two items) to decide which item is the smallest.
Tip: Use the max() method to find the largest item.
Syntax
One of the following:
public static T min(Collection<T> c)
public static T min(Collection<T> c, Comparator comp)
T refers to the data type of items in the collection.
Parameter Values
| Parameter | Description |
|---|---|
| c | Required. The collection to search in. |
| comp | Optional. A Comparator that decides the order of the items. |
Technical Details
| Returns: | The smallest item in the collection. |
|---|---|
| Throws: | NoSuchElementException - if the collection is empty. |
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods