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
// Java code to illustrate the keySet() method // to get Set view of Keys from a Hashtable. 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) { // Creating an empty Hashtable Hashtable<String, String> hash_t = new Hashtable<String, String>(); // Add mappings into the table hash_t.put( "1" , "Geeks" ); hash_t.put( "2" , "For" ); hash_t.put( "3" , "Geeks" ); // Getting a Set of keys using // keySet() method of Hashtable class Set hash_set = hash_t.keySet(); System.out.println( "Set created from Hashtable Keys contains :" ); // Iterating through the Set of keys Iterator itr = hash_set.iterator(); while (itr.hasNext()) System.out.println(itr.next()); } } |
Set created from Hashtable Keys contains : 3 2 1
Example 2:
Java
// Java code to illustrate the keySet() method // to get Set view of Keys from a Hashtable. 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) { // Creating an empty Hashtable Hashtable<String, String> hash_t = new Hashtable<String, String>(); // Inserting elements into the table hash_t.put( "Geeks" , "1" ); hash_t.put( "For" , "2" ); hash_t.put( "geeks" , "3" ); // Getting a Set of keys using // keySet() method of Hashtable class Set hash_set = hash_t.keySet(); System.out.println( "Set created from Hashtable Keys contains :" ); // Iterating through the Set of keys Iterator itr = hash_set.iterator(); while (itr.hasNext()) System.out.println(itr.next()); } } |
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.