VOOZH about

URL: https://www.geeksforgeeks.org/java/collections-min-method-in-java-with-examples/

⇱ Collections min() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Collections min() method in Java with Examples

Last Updated : 10 Oct, 2018

min(Collection<? extends T> coll)

The min() method of java.util.Collections class is used to return the minimum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the collection). This method iterates over the entire collection, hence it requires time proportional to the size of the collection. Syntax:
public static <T 
 extends Object & Comparable<? super T>> T 
 min(Collection<? extends T> coll)
Parameters: This method takes the collection coll as a parameter whose minimum element is to be determined Return Value: This method returns the minimum element of the given collection, according to the natural ordering of its elements. Exception: This method throws NoSuchElementException if the collection is empty. Below are the examples to illustrate the min() method Example 1:
Output:
List: [10, 20, 30, 40]
Minimum value is: 10
Example 2: To demonstrate NoSuchElementException
Output:
List: []
Trying to get the minimum value with empty list
Exception thrown : java.util.NoSuchElementException

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

The min(Collections, Comparator) method of java.util.Collections class is used to return the minimum element of the given collection, according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator . This method iterates over the entire collection, hence it requires time proportional to the size of the collection. Parameters: This method takes the following argument as parameters:
  • coll- the collection whose minimum element is to be determined.
  • comp- the comparator with which to determine the minimum element. A null value indicates that the elements' natural ordering should be used.
Return Value: This method returns the minimum element of the given collection, according to the specified comparator. Exception: This method throws NoSuchElementException if the collection is empty. Below are the examples to illustrate the min() method Example 1:
Output:
List: [10, 20, 30, 40]
Min value by reverse order is: 40
Example 2: To demonstrate NoSuchElementException
Output:
List: []
Trying to get the minimum value with empty list
Exception thrown : java.util.NoSuchElementException
Comment