Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Find Minimum Element of ArrayList with Java Collections



In order to compute minimum element of ArrayList with Java Collections, we use the Collections.min() method. The java.util.Collections.min() returns the minimum element of the given collection. All elements must be mutually comparable and implement the comparable interface. They shouldn’t throw a ClassCastException.

Declaration −The Collections.min() method is declared as follows −

public static <T extends Object & Comparable> T min(Collection c)

where c is the collection object whose minimum is to be found.

Let us see a program to find the minimum element of ArrayList with Java collections −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      List<Integer> list = new ArrayList<Integer>();
      try {
         list.add(14);
         list.add(2);
         list.add(73);
         System.out.println("Minimum element : " + Collections.min(list));
      }
      catch (ClassCastException | NoSuchElementException e) {
         System.out.println("Exception caught : " + e);
      }
   }
}

Output

Minimum element : 2
Updated on: 2020-06-25T14:37:35+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements