How to get maximum element from ArrayList

In this article, we will discuss how to get maximum element from ArrayList using Collections class’s utility max() method

 

To get maximum element from ArrayList :

Method signature:

public static Object max(Collection coll);

GetMaxFromArrayList.java

package in.bench.resources.java.collections;

import java.util.ArrayList;
import java.util.Collections;

public class GetMaxFromArrayList {

	public static void main(String[] args) {

		// creating ArrayList object of type Integer
		ArrayList<Integer> al = new ArrayList<Integer>();

		// adding elements to ArrayList object
		al.add(31);
		al.add(83);
		al.add(53);
		al.add(29);
		al.add(7);
		al.add(97);
		al.add(13);
		al.add(47);
		al.add(79);

		// getting max value from AL 
		Integer iMaxValueFromAL = Collections.max(al);

		// printing to console
		System.out.println("Maximum value from ArrayList : " 
				+ iMaxValueFromAL);
	}
}

Output:

Maximum value from ArrayList : 97

Note:

  • Integer object and int primitive gets converted automatically using Auto-boxing & un-boxing features
  • which is introduced in Java 1.5 version

 

References:

 

Happy Coding !!
Happy Learning !!

How to get minimum element from ArrayList
Converting Ordered ArrayList into Sorted TreeSet