Java Utility Library

Java Collections - min() Method



The java.util.Collections.min() method returns the minimum element of the given collection, according to the natural ordering of its elements.

Syntax

public static <T extends Object & Comparable<? super T>> 
              T min(Collection<? extends T> coll)

Here, T is the type of element in the collection.


Parameters

coll Specify the collection whose minimum element is to be determined.

Return Value

Return the minimum element of the given collection, according to the natural ordering of its elements.

Exception

  • Throws ClassCastException, if the collection contains elements that are not mutually comparable (for example, strings and integers).
  • Throws NoSuchElementException, if the collection is empty.

Example:

In the example below, the java.util.Collections.min() method is used to find the minimum element in a given collection according to the natural ordering of its elements.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list object
    List<Integer> MyList = new ArrayList<Integer>();

    //populating MyList
    MyList.add(10);
    MyList.add(20);
    MyList.add(-30);
    MyList.add(-40);
    MyList.add(100);

    //printing the list
    System.out.println("MyList contains: " + MyList);  

    //finding minimum element in the list
    int retval = Collections.min(MyList);
    System.out.println("Minimum element in MyList: " + retval); 
  }
}

The output of the above code will be:

MyList contains: [10, 20, -30, -40, 100]
Minimum element in MyList: -40

❮ Java.util - Collections