How to Find the Minimum or Maximum Element from LinkedHashSet in Java?
Last Updated :
10 May, 2021
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.
Following Java code finds the minimum and maximum element from LinkedHashSet using predefined min, max method of the Collections class.
Java
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
LinkedHashSet<Integer> lhs
= new LinkedHashSet<Integer>();
lhs.add( 1 );
lhs.add( 56 );
lhs.add( 8 );
lhs.add( 24 );
lhs.add( 50 );
int maximum = Collections.max(lhs);
int minimum = Collections.min(lhs);
System.out.println( "Maximum element: " + maximum);
System.out.println( "Minimum element: " + minimum);
}
}
|
Output
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
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
LinkedHashSet<Integer> lhs
= new LinkedHashSet<Integer>();
lhs.add( 1 );
lhs.add( 56 );
lhs.add( 8 );
lhs.add( 24 );
lhs.add( 50 );
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);
}
}
|
Output
Maximum element: 56
Minimum element: 1
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...