.max()
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
Contribute to Docs
- 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.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours