Java Utility Library

Java Collections - min() Method



The java.util.Collections.min() method returns the minimum element of the given collection, according to the order induced by the specified comparator.

Syntax

public static <T> T min(Collection<? extends T> coll, 
                        Comparator<? super T> comp)

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


Parameters

coll Specify the collection whose minimum element is to be determined.
comp Specify the comparator with which to determine the minimum element. A null value indicates that the elements' natural ordering should be used.

Return Value

Return the minimum element of the given collection, according to the specified comparator.

Exception

  • Throws ClassCastException, if the collection contains elements that are not mutually comparable using the specified comparator.
  • 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 specified comparator.

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);  

    //creating a comparator for natural order sorting
    Comparator<Integer> comp = Comparator.naturalOrder();

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

The output of the above code will be:

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

❮ Java.util - Collections