Hashtable keySet() Method in Java with Examples
Last Updated :
15 Oct, 2020
The java.util.Hashtable is used to create a set of key elements in the hash table. It basically returns a set view of the keys, or we can create a new set and store the key elements in them.
Syntax:
public Set<K> keySet()
K : type of the Keys in the hash table
Parameters: The method does not take any parameter.
Return Value: The method returns a set having the keys of the hash table.
Below programs are used to illustrate the working of java.util.Hashtable.keySet() Method:
Example 1:
Java
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Hashtable;
import java.util.Set;
public class Example1 {
public static void main(String[] args)
{
Hashtable<String, String> hash_t
= new Hashtable<String, String>();
hash_t.put( "1" , "Geeks" );
hash_t.put( "2" , "For" );
hash_t.put( "3" , "Geeks" );
Set hash_set = hash_t.keySet();
System.out.println(
"Set created from Hashtable Keys contains :" );
Iterator itr = hash_set.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
|
Output
Set created from Hashtable Keys contains :
3
2
1
Example 2:
Java
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Hashtable;
import java.util.Set;
public class Example2 {
public static void main(String[] args)
{
Hashtable<String, String> hash_t
= new Hashtable<String, String>();
hash_t.put( "Geeks" , "1" );
hash_t.put( "For" , "2" );
hash_t.put( "geeks" , "3" );
Set hash_set = hash_t.keySet();
System.out.println(
"Set created from Hashtable Keys contains :" );
Iterator itr = hash_set.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
|
Output
Set created from Hashtable Keys contains :
For
Geeks
geeks
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...