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.