Finding Maximum Element of Java HashSet
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 maximum element in a HashSet.
Input: [24, 56, 87, 64, 29, 2, 65]
Output: 87
Input: [45, 3, 65, 32, 64, 12, 43]
Output: 65
Methods:
- Using a For-each loop (Naive approach)
- Using Collection.max() 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 MIN_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 max = Integer.MIN_VALUE;
for ( int var : gfg) {
if (var > max)
max = var;
}
System.out.println( "Maximum element in HashSet = "
+ max);
}
}
|
Output
Elements in HashSet = [64, 65, 2, 87, 24, 56, 29]
Maximum element in HashSet = 87
Time Complexity: O(n) where n is a number of elements in a HashSet.
Method 2: Using Collection.max() method of HashSet of collection class.
Syntax:
public static <T extends Object & Comparable> T max(Collection coll)
Parameters: This method takes the collection coll as a parameter whose maximum element is to be determined.
Return Value: This method returns the maximum element of the given collection, according to the natural ordering of its elements.
Exception: This method throws the following Exception:
Approach:
- Create an object of HashSet
- Add elements to the object created
- Use Collection.max() method to display the largest 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.max(gfg);
System.out.println( "Maximum element :" + obj);
}
}
|
Output
Elements in HashSet = [Geekss, Geek, Geeks]
Maximum element :Geekss
Last Updated :
13 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...