Tag Archives: java.util.Collections.max()

java.util.Collections.max() [How to Use]

Description

max(Collection<? extends T>)   Method is used to return the largest element of a given set according to the natural order of its elements.

Manifesto

The following is the declaration of the Java. Util. Collections. Max () method.

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

Parameters

coll  – The set whose largest element is to be determined.

Return value

Method call returns the largest element of a given collection, according to the natural order of its elements.

Exception

ClassCastException  – This exception is thrown if the collection contains elements that are not comparable to each other, such as strings and integers. NoSuchElementException  – If the collection is empty, this exception is thrown.

example

The following example shows the usage of Java. Util. Collections. Max()

import java.util.*;

public class CollectionsDemo {
   public static void main(String args[]) { 
      
      // create link list object 
      LinkedList<Integer> list = new LinkedList<Integer>();

      // populate the list  
      list.add(-18);  
      list.add(40);  
      list.add(-45);  
      list.add(12); 

      System.out.println("Max value is: " + Collections.max(list));          
   }  
}

Let’s compile and run the above program, which will produce the following result.

Max value is: 40