Java .max()
Published Jul 18, 2022
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
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours