Way2Java

Find Min Max values with min() max()

There comes two methods from Collections class to find the elements with minimum and maximum values of a data structure. These methods can be applied to any Collection class (subclasses of Collection interface). In the following code ArrayList is used.

Following are the method signatures.

Example on Find Min Max values with min() max() meethods
import java.util.*;
public class CollectionsMaxMin
{
  public static void main(String args[])
  {
    ArrayList firstList = new ArrayList();
    firstList.add(50);
    firstList.add(10);
    firstList.add(20);
    System.out.println("Elements firstList: " + firstList);

    System.out.println("Minimum value element firstList: " + Collections.min(firstList));
    System.out.println("Maximum value element firstList: " + Collections.max(firstList));

    ArrayList secondList = new ArrayList();
    secondList.add("five");
    secondList.add("two");
    secondList.add("six");
    System.out.println("\nElements secondList: " + secondList);

    System.out.println("Minimum value element secondList: " + Collections.min(secondList));
    System.out.println("Maximum value element secondList: " + Collections.max(secondList));
  }
}



Output screenshot on Find Min Max values with min() max()

ArrayList firstList = new ArrayList();
firstList.add(50); firstList.add(10); firstList.add(20);

An ArrayList object, firstList, is created with three integer elements 50, 10 and 20.

Collections.min(firstList);
Collections.max(firstList);

The min() and max() methods returns 10 and 50, the minimum and maximum values of firstList.

ArrayList secondList = new ArrayList();
secondList.add(“five”); secondList.add(“two”); secondList.add(“six”);

Another ArrayList object secondList is created with string elements "five", "two", and "six".

Collections.min(secondList);
Collections.max(secondList);

The above min() and max() methods with respect strings print five and two because f comes before t and s and last comes is t (after s). It is alphabetical order sorting.