Collections

Find minimum and maximum elements of Collection example

With this example we are going to demonstrate how to find minimum and maximum elements of a Collection. We are using an ArrayList, but the same API applies to any type of Collection implementation class e.g. HashSet, TreeSet, LinkedHashSet, LinkedList, Vector etc. In short, to find minimum and maximum elements of a Collection you should:

  • Create an ArrayList.
  • Populate the arrayList with elements, with add(E e) API method of ArrayList.
  • Invoke the min(Collection c) API method of Collections to get the minimum element of the provided ArrayList according to its elements natural ordering.
  • Invoke the max(Collection c) API method of Collections to get the maximum element of the ArrayList according to its elements natural ordering.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.ArrayList;
import java.util.Collections;
 
public class MinMaxElementOfCollection {
 
  public static void main(String[] args) {

    /*

Please note that the same API applies to any type of 

Collection implementation class e.g. 

HashSet, TreeSet, LinkedHashSet, LinkedList, Vector etc
     */
 
    // Create an ArrayList and populate it with elements
    ArrayList arrayList = new ArrayList();
    arrayList.add("element_1");
    arrayList.add("element_3");
    arrayList.add("element_4");
    arrayList.add("element_2");
    arrayList.add("element_5");
 
    // static Object min(Collection c) method returns the minimum element of the provided Collection according to its elements natural ordering
    Object minimum = Collections.min(arrayList);

    // static Object max(Collection c) method returns the maximum element of Java ArrayList according to  its elements natural ordering
    Object maximum = Collections.max(arrayList);
 
    System.out.println("Minimum element of ArrayList : " + minimum + ", Maximum Element of ArrayList : " + maximum);
  }
}

Output:

Minimum element of ArrayList : element_1, Maximum Element of ArrayList : element_5

 
This was an example of how to find minimum and maximum elements of a Collection in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button