Finding Minimum Element of Java HashSet
Last Updated :
28 Dec, 2020
Java HashSet class is used to create collection to be used by the collection that uses a hash table for storage purposes that uses the mechanism known as hashing. The implementation class of Set. It inherits the abstract class and implements et interface. The main trait is it does not allow duplicates and uses a hash table internally.
Illustration: find minimum element in a HashSet.
Example:
Input : [24, 56, 87, 64, 29, 2, 65]
Output : 2
Input : [45, 3, 65, 32, 64, 12, 43]
Output : 3
Methods:
- Using a For-each loop (Naive approach)
- Using Collection.min() method of HashSet (Optimal approach)
Method 1: Using for-loop to print maximum element in a HashSet.
Approach:
- Create an object of HashSet
- Add elements to the object created
- Create a variable and assign it with the value MAX_VALUE
- Iterate using for each loop
Remember :
- In computing maximum assign -∞ as initial max
- In computing minimum assign +∞ as initial min
Example 1
Java
import java.io.*;
import java.util.Collections;
import java.util.HashSet;
class GFG {
public static void main(String[] args)
{
HashSet<Integer> gfg = new HashSet<Integer>();
gfg.add( 24 );
gfg.add( 56 );
gfg.add( 87 );
gfg.add( 64 );
gfg.add( 29 );
gfg.add( 2 );
gfg.add( 65 );
System.out.println( "Elements in HashSet = " + gfg);
int min = Integer.MAX_VALUE;
for ( int var : gfg) {
if (var < min)
min = var;
}
System.out.println( "Minimum element in HashSet = "
+ min);
}
}
|
Output
Elements in HashSet = [64, 65, 2, 87, 24, 56, 29]
Minimum element in HashSet = 2
Time Complexity: O(n) where n is a number of elements in a HashSet.
Method 2: Using Collection.min() method of HashSet of collection class.
Syntax:
public static <T extends Object & Comparable<? super T>> T
min(Collection<? extends T> coll)
Parameters: This method takes the collection coll as a parameter whose minimum element is to be determined
Return Value: This method returns the minimum element of the given collection, according to the natural ordering of its elements.
Exception: This method throws NoSuchElementException if the collection is empty.
Approach:
- Create an object of HashSet
- Add elements to the object created
- Use Collection.min() method to display the smallest string among the non-duplicated list generated after creating. Note there will be no single duplicate element.
Example 2
Java
import java.io.*;
import java.util.Collections;
import java.util.HashSet;
class GFG {
public static void main(String[] args)
{
HashSet<String> gfg = new HashSet<String>();
gfg.add( "Geekss" );
gfg.add( "Geeks" );
gfg.add( "Geek" );
System.out.println( "Elements in HashSet = " + gfg);
Object obj = Collections.min(gfg);
System.out.println( "Minimum String in a HashSet :"
+ obj);
}
}
|
Output
Elements in HashSet = [Geekss, Geek, Geeks]
Minimum String in a HashSet :Geek
Share your thoughts in the comments
Please Login to comment...