Given a LinkedHashSet the task is to find the minimum and maximum element from this LinkedHashSet in Java. There are two ways to find the minimum or maximum element from LinkedHashSet in Java as follows
- Using the min and max method of the Collections class
- By Iterating the LinkedHashSet
Examples:
Input : LinkedHashset : {1, 56, 8, 24, 50} Output: Maximum Element: 56 Minimum Element: 1 Input : LinkedHashset : {2, 34, 100, 29, 30} Output: Maximum Element: 100 Minimum Element: 2
Approach 1:
The max and min method of the Collections class returns the maximum and minimum element of the specified collection object.
- Collections.max(Object obj): Accepts the collection object.
- Collections.min(Object obj): Accepts the collection object.
Following Java code finds the minimum and maximum element from LinkedHashSet using predefined min, max method of the Collections class.
Java
// Java Program to find the minimum or // maximum element from LinkedHashSe import java.io.*; import java.util.*; class Main { public static void main(String[] args) { // create a new LinkedHashSet LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>(); // add elements to LinkedHashSet lhs.add( 1 ); lhs.add( 56 ); lhs.add( 8 ); lhs.add( 24 ); lhs.add( 50 ); // finding maximum and minimum using inbuilt // functions int maximum = Collections.max(lhs); int minimum = Collections.min(lhs); System.out.println( "Maximum element: " + maximum); System.out.println( "Minimum element: " + minimum); } } |
Maximum element: 56 Minimum element: 1
Approach 2:
Iterate over the LinkedHashSet using enhanced for loop or iterator and find the maximum and minimum element.
Consider the following Java code which finds the maximum and minimum element by iterating over each element in the LinkedHashSet.
Java
// Java Program to find the minimum or // maximum element from LinkedHashSet import java.io.*; import java.util.*; class Main { public static void main(String[] args) { // create a new LinkedHashSet LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>(); // add elements to LinkedHashSet lhs.add( 1 ); lhs.add( 56 ); lhs.add( 8 ); lhs.add( 24 ); lhs.add( 50 ); // Iterate over the LinkedHashSet int maximum = Integer.MIN_VALUE; int minimum = Integer.MAX_VALUE; for (Integer num : lhs) { if (maximum < num) maximum = num; } for (Integer num : lhs) { if (minimum > num) minimum = num; } System.out.println( "Maximum element: " + maximum); System.out.println( "Minimum element: " + minimum); } } |
Maximum element: 56 Minimum element: 1