How to Find the Minimum and Maximum Value from Java HashSet?
HashSet is used to store distinct values in Java. The HashSet does not guarantee the constant order of elements over time, which means when we iterate a HashSet, there is no guarantee that we get the same order of elements as we added in order. HashSet does not provide any built-in method to get the maximum and minimum values.
There are a couple of ways to find the maximum and minimum from the HashSet in Java:
- Using Collection class
- Using simple iteration
Method 1: Using Collections class
Using Collections class in Java we can find maximum and minimum value with the help of max() and min() method of Collections class.
Code:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashSet<Integer> set = new HashSet<>();
set.add( 10 );
set.add( 20 );
set.add( 20 );
set.add( 10 );
set.add( 50 );
set.add( 40 );
System.out.println( "Maximum value of HashSet : "
+ Collections.max(set));
System.out.println( "Minimum value of HashSet : "
+ Collections.min(set));
}
}
|
Output
Maximum value of HashSet : 50
Minimum value of HashSet : 10
Method 2: Using Simple Iteration
We can find Maximum and Minimum using simply iterate the HashSet and maintain the min and max variable and update it accordingly while traversing through each element and comparing it with the min and max values.
Code:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashSet<Integer> set = new HashSet<>();
set.add( 10 );
set.add( 20 );
set.add( 20 );
set.add( 10 );
set.add( 50 );
set.add( 40 );
int max = - 1 , min = - 1 ;
for ( int val : set) {
if (max == - 1 ) {
max = val;
}
else if (val > max) {
max = val;
}
}
for ( int val : set) {
if (min == - 1 ) {
min = val;
}
else if (val < min) {
min = val;
}
}
System.out.println( "Maximum value of HashSet : "
+ max);
System.out.println( "Minimum value of HashSet : "
+ min);
}
}
|
Output
Maximum value of HashSet : 50
Minimum value of HashSet : 10
Last Updated :
28 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...