Collections max() method in Java with Examples - GeeksforGeeks

11 May, 2021
The max() method of java.util.Collections class is used to return the maximum 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> T
  max(Collection coll)
Parameters: This method takes the collection coll as a parameter whose maximum element is to be determined.Return Value: This method returns the maximum element of the given collection, according to the natural ordering of its elements.
Exception: This method throws following Exception:  
ClassCastException – if the collection contains elements that are not mutually comparable (for example, strings and integers).
NoSuchElementException – if the collection is empty
Below are the examples to illustrate the max() method
Example 1:  
Java
// Java program to demonstrate// max() method for Integer value import java.util.*; public class GFG1 {    public static void main(String[] argv)        throws Exception    {         try {             // creating object of LinkedList            List<Integer> list = new LinkedList<Integer>();             // Adding element to Vector v            list.add(-1);            list.add(4);            list.add(-5);            list.add(1);             // printing the max value            // using max() method            System.out.println("Max value is: "                               + Collections.max(list));        }         catch (ClassCastException e) {            System.out.println("Exception thrown : " + e);        }         catch (NoSuchElementException e) {            System.out.println("Exception thrown : " + e);        }    }}
Max value is: 4
 
Example 2: for ClassCastException 
Java
// Java program to demonstrate// max() method for ClassCastException import java.util.*; public class GFG1 {    public static void main(String[] argv)        throws Exception    {         try {             // creating object of LinkedList            List<String> list = new LinkedList<String>();             // creating variable of object type            Object i = Integer.valueOf(42);             // Adding element to Vector v            list.add("Hello");            list.add((String)i);             // printing the max value            // using max() method            System.out.println("Max value is: "                               + Collections.max(list));        }         catch (ClassCastException e) {            System.out.println("Exception thrown : " + e);        }         catch (NoSuchElementException e) {            System.out.println("Exception thrown : " + e);        }    }}
Exception thrown : java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
 
Example 3: for NoSuchElementException 
Java
// Java program to demonstrate// max() method for NoSuchElementException import java.util.*; public class GFG1 {    public static void main(String[] argv)        throws Exception    {         try {             // creating object of LinkedList            List<Integer> list = new LinkedList<Integer>();             // printing the max value            // using max() method            System.out.println("Trying to get "                               + "the max from empty list");            System.out.println("Max value is: "                               + Collections.max(list));        }         catch (ClassCastException e) {            System.out.println("Exception thrown : " + e);        }         catch (NoSuchElementException e) {            System.out.println("Exception thrown : " + e);        }    }}
Trying to get the max from empty list
Exception thrown : java.util.NoSuchElementException
 
The max() method of java.util.Collections class is used to return the maximum 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 (that is, comp.compare(e1, 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.
Parameters: This method takes the following argument as a parameter 
coll – the collection whose maximum element is to be determined.
comp – the comparator with which to determine the maximum element. A null value indicates that the elements’ natural ordering should be used.
Return Value: This method returns the maximum element of the given collection, according to the specified comparator.
Exception: This method throws following Exception:  
ClassCastException – if the collection contains elements that are not mutually comparable (for example, strings and integers).
NoSuchElementException – if the collection is empty
Below are the examples to illustrate the max() method
Example 1:  
Java
// Java program to demonstrate// max() method for Integer value import java.util.*; public class GFG1 {    public static void main(String[] argv)        throws Exception    {         try {             // creating object of LinkedList            List<Integer> list = new LinkedList<Integer>();             // Adding element to Vector v            list.add(-1);            list.add(4);            list.add(-5);            list.add(1);             // printing the max value            // using max() method            System.out.println("Max val: "                               + Collections.max(list,                                                 Collections.reverseOrder()));        }         catch (ClassCastException e) {            System.out.println("Exception thrown : " + e);        }         catch (NoSuchElementException e) {            System.out.println("Exception thrown : " + e);        }    }}
Max val: -5
 
Example 2: for ClassCastException 
Java
// Java program to demonstrate// max() method for ClassCastException import java.util.*; public class GFG1 {    public static void main(String[] argv)        throws Exception    {         try {             // creating object of LinkedList            List<String> list = new LinkedList<String>();             // creating variable of object type            Object i = Integer.valueOf(42);             // Adding element to Vector v            list.add("Hello");            list.add((String)i);             // printing the max value            // using max() method            System.out.println("Max val: "                               + Collections                                     .max(list,                                          Collections                                              .reverseOrder()));        }         catch (ClassCastException e) {            System.out.println("Exception thrown : " + e);        }         catch (NoSuchElementException e) {            System.out.println("Exception thrown : " + e);        }    }}
Exception thrown : java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
 
Example 3: for NoSuchElementException 
Java
// Java program to demonstrate// max() method for NoSuchElementException import java.util.*; public class GFG1 {    public static void main(String[] argv)        throws Exception    {         try {             // creating object of LinkedList            List<Integer> list = new LinkedList<Integer>();             // printing the max value            // using max() method            System.out.println("Trying to get "                               + "the max from empty list");            System.out.println("Max val: "                               + Collections                                     .max(list,                                          Collections                                              .reverseOrder()));        }         catch (ClassCastException e) {            System.out.println("Exception thrown : " + e);        }         catch (NoSuchElementException e) {            System.out.println("Exception thrown : " + e);        }    }}
Trying to get the max from empty list
Exception thrown : java.util.NoSuchElementException
 
Akanksha_Rai
sweetyty
Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java