Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Finding Maximum Element of Java ArrayList

  • Difficulty Level : Easy
  • Last Updated : 11 May, 2021

For finding the maximum element in the ArrayList, complete traversal of the ArrayList is required. There is an inbuilt function in the ArrayList class to find the maximum element in the ArrayList, i.e. Time Complexity is O(N), where N is the size of ArrayList, Let’s discuss both the methods.

Example:

Input : ArrayList = {2, 9, 1, 3, 4}
Output: Max = 9

Input : ArrayList = {6, 7, 2, 1}
Output: Max = 7

Approach 1:

  1. Create on variable and initialize it with the first element of ArrayList.
  2. Start traversing the ArrayList.
  3. If the current element is greater than variable, then update the variable with the current element in ArrayList.
  4. In the end, print that variable.

Below is the implementation of the above approach:

Java




// Finding Maximum Element of Java ArrayList
import java.util.ArrayList;
import java.util.Collections;
 
class MinElementInArrayList {
 
    public static void main(String[] args)
    {
        // ArrayList of Numbers
        ArrayList<Integer> myList
            = new ArrayList<Integer>();
 
        // adding elements to Java ArrayList
        myList.add(16);
        myList.add(26);
        myList.add(3);
        myList.add(52);
        myList.add(70);
        myList.add(12);
 
        int maximum = myList.get(0);
        for (int i = 1; i < myList.size(); i++) {
            if (maximum < myList.get(i))
                maximum = myList.get(i);
        }
        System.out.println("Maximum Element in ArrayList = "
                           + maximum);
    }
}
Output
Maximum Element in ArrayList = 70

Approach 2:

The max method of the Java collection class can be used to find ArrayList. The max method returns the maximum element of the collection according to the natural ordering of the elements.

Java




// Finding Maximum Element of Java ArrayList
import java.util.ArrayList;
import java.util.Collections;
 
class MinElementInArrayList {
 
    public static void main(String[] args)
    {
 
        // ArrayList of Numbers
        ArrayList<Integer> myList
            = new ArrayList<Integer>();
 
        // adding elements to Java ArrayList
        myList.add(16);
        myList.add(26);
        myList.add(3);
        myList.add(52);
        myList.add(70);
        myList.add(12);
 
        // 'min' method is used to find the
        // minimum elementfrom Collections Class
        System.out.println("Maximum Element in ArrayList = "
                           + Collections.max(myList));
    }
}
Output
Maximum Element in ArrayList = 70

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!