Java Utility Library

Java Collections - max() Method



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

Syntax

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

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


Parameters

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

Return Value

Return the maximum 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.max() method is used to find the maximum 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 maximum element in the list
    int retval = Collections.max(MyList);
    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: 100

❮ Java.util - Collections