Java Collections - max() Method
The java.util.Collections.max() method returns the maximum element of the given collection, according to the order induced by the specified comparator.
Syntax
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)
Here, T is the type of element in the collection.
Parameters
coll |
Specify the collection whose maximum element is to be determined. |
comp |
Specify the comparator with which to determine the maximum element. A null value indicates that the elements' natural ordering should be used. |
Return Value
Return the maximum 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.max() method is used to find the maximum 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 maximum element in the list int retval = Collections.max(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: 100
❮ Java.util - Collections