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 code to find the maximum and minimum in HashSet import java.util.*;
public class GFG {
public static void main(String[] args)
{
// New HashSet
HashSet<Integer> set = new HashSet<>();
// Add data to Hashset
set.add( 10 );
set.add( 20 );
set.add( 20 );
set.add( 10 );
set.add( 50 );
set.add( 40 );
// Print Maximum value using max method of
// Collections class
System.out.println( "Maximum value of HashSet : "
+ Collections.max(set));
// Print Maximum value using max method of
// Collections class
System.out.println( "Minimum value of HashSet : "
+ Collections.min(set));
}
} |
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 code to find the maximum and minimum in HashSet import java.util.*;
public class GFG {
public static void main(String[] args)
{
// New HashSet
HashSet<Integer> set = new HashSet<>();
// Add data to Hashset
set.add( 10 );
set.add( 20 );
set.add( 20 );
set.add( 10 );
set.add( 50 );
set.add( 40 );
int max = - 1 , min = - 1 ;
// Iterate HashSet to get Maximum value
for ( int val : set) {
if (max == - 1 ) {
max = val;
}
else if (val > max) {
max = val;
}
}
// Iterate HashSet to get Minimum value
for ( int val : set) {
if (min == - 1 ) {
min = val;
}
else if (val < min) {
min = val;
}
}
// Print Maximum value using max method of
// Collections class
System.out.println( "Maximum value of HashSet : "
+ max);
// Print Maximum value using max method of
// Collections class
System.out.println( "Minimum value of HashSet : "
+ min);
}
} |
Maximum value of HashSet : 50 Minimum value of HashSet : 10