Open In App

Finding Minimum Element of Java ArrayList

Improve
Improve
Like Article
Like
Save
Share
Report

For finding the minimum element in the ArrayList(This class is found in java.util package), complete traversal of the ArrayList is required. There is an inbuilt function in ArrayList class to find minimum 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: Min = 1

Input : ArrayList = {6, 7, 2, 8}
Output: Min = 2

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 less 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 Minimum 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 minimum = myList.get(0);
        for (int i = 1; i < myList.size(); i++) {
            if (minimum > myList.get(i))
                minimum = myList.get(i);
        }
        System.out.println("Minimum element in ArrayList = "
                           + minimum);
    }
}


Output

Minimum element in ArrayList = 3

 

Approach 2:

‘min’ method of java collection class can be used to find ArrayList. ‘min’ method returns the minimum element of the collection according to the natural ordering of the elements.

Java




// Finding Minimum 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 element
        // from Collections Class
        System.out.println("Minimum Element in ArrayList = "
                           + Collections.min(myList));
    }
}


Output

Minimum Element in ArrayList = 3


Last Updated : 04 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads