In this example we will show how to find a maximum element of java ArrayList with max method of Collections class.
Source Code
1)
package com.beginner.examples;
import java.util.ArrayList;
import java.util.Collections;
public class FindMaxElementOfArrayList1 {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(6);
al.add(3);
al.add(5);
al.add(9);
al.add(8);
// Use the sort() method in the Collections utility class to sort from
// smallest to largest
Collections.sort(al);
//Gets the element of the last index
//This element right here is the largest element
Integer max = al.get(al.size() - 1);
System.out.println("Max:"+max);
}
}
Output:
Max:9
2)
package com.beginner.examples;
import java.util.ArrayList;
import java.util.Collections;
public class FindMaxElementOfArrayList2 {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(6);
al.add(3);
al.add(5);
al.add(9);
al.add(8);
// Use the Max () method in the Collections class to get the largest
// element
Integer max = Collections.max(al);
System.out.println("Max:" + max);
}
}
Output:
Max:9
References
Imported packages in Java documentation: