The max() and min() methods of the java.util.Collections class are used to return the maximum and minimum element, respectively, of a given collection based on the natural ordering of its elements. The methods can be used with various collection interfaces like LinkedList, ArrayList, HashSet, ArrayDeque, etc. However, all elements in the collection must implement the Comparable interface, and they must be mutually comparable.
Example 1:
The following code demonstrates the usage of the max() method with an ArrayList of integers:
javaimport java.util.*;
public class GFG {
public static void main(String[] argv)
{
// Creating object of ArrayList
List<Integer> list = new ArrayList<Integer>();
// Adding elements to the list
list.add(10);
list.add(5);
list.add(20);
// Printing the maximum value using the max() method
System.out.println(Collections.max(list));
}
}
Output:
20
Example 2:
The following code demonstrates the usage of the min() method with an ArrayList of integers:
csharpimport java.util.*;
public class GFG {
public static void main(String[] argv)
{
// Creating object of ArrayList
List<Integer> list = new ArrayList<Integer>();
// Adding elements to the list
list.add(10);
list.add(5);
list.add(20);
// Printing the minimum value using the min() method
System.out.println(Collections.min(list));
}
}
Output:
5
Example 3:
The following code demonstrates the usage of the max() method with a list containing user-defined objects. Here, we have defined a Point class that implements the Comparable interface and overrides the compareTo() function to define the nature of order according to the x-coordinate.
javaimport java.util.*;
import java.lang.*;
import java.io.*;
class Point implements Comparable<Point>
{
int x, y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}
// compareTo() function defining the
// nature of order i.e., according to
// x-coordinate
public int compareTo(Point p)
{
return this.x - p.x;
}
}
class GFG {
public static void main(String[] argv)
{
// Creating object of ArrayList
List<Point> list = new ArrayList<Point>();
// Adding elements to the list
list.add(new Point(5, 20));
list.add(new Point(25, 10));
list.add(new Point(10, 40));
Point p = Collections.max(list);
// Replacing the above with this
// Point p = Collections.min(list);
// gives the minimum pair
// Printing the maximum value using the max() method
System.out.println(p.x + " " + p.y);
}
}
Output:
25 10
Example 4:
The following code demonstrates the usage of the max() method with a list containing user-defined objects that do not implement the Comparable interface. Here, we have defined a Point class that is not comparable. To sort the objects according to their x-coordinate, we have implemented a MyCmp class that implements the Comparator interface.
javaimport java.util.*;
import java.lang.*;
import java.io.*;
class Point
{
int x, y;
Point(int x, int y)
{
this.x = x;