.max()
StevenSwiniarski466 total contributions
Published Jul 18, 2022
Contribute to Docs
The Collections.max()
method returns the maximum member of a List
based on natural ordering or based on a Comparator. To use natural ordering, the elements of the List
must implement the Comparable interface.
Syntax
import java.util.*;
// This provides the maximum element via natural ordering
myMax = Collections.max(myList);
// This provides the maximum element via a Comparator
myMax = Collections.max(myList, myComparator);
Both methods return the maximum element of myList
. The first determines the maximum element using the natural ordering of the elements. The second uses myComparator
to determine the maximum.
Example
The following example creates an ArrayList
and then uses Collections.max()
to return some elements:
import java.util.*;public class Main {public static void main(String[] args) {ArrayList<String> food = new ArrayList<String>();food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");System.out.println(Collections.max(food));food.remove("Sausage");System.out.println(Collections.max(food));}}
This will output the following:
SausageSalad
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.