Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is the HashTable.keys() method in Java?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The HashTable.keys() method is present in the HashTable class inside the java.util package.

HashTable.keys() is used to get the enumerationa complete, ordered listing of all the items in a collection of the keys present in the HashTable.

Parameters

HashTable.keys() does not take any parameters.

Return value

HashTable.keys() returns an enumeration of keys in the HashTable.

Code

Let’s look at the code snippet below.

import java.util.*;
class Main
{
public static void main(String[] args)
{
Hashtable<Integer, String> h1 = new Hashtable<Integer, String>();
h1.put(1, "Let's");
h1.put(5, "see");
h1.put(2, "Hashtable.keys()");
h1.put(27, "method");
h1.put(9, "in java.");
System.out.println("The Hashtable is: " + h1);
Enumeration e = h1.keys();
System.out.print("The enumeration of keys are:");
while (e.hasMoreElements())
System.out.print(e.nextElement()+" ");
}
}
Using the HashTable.keys() method in Java

Explanation

  • In line 1, we import the required package.
  • In line 2, we make a Main class.
  • In line 4, we make a main function.
  • In line 6, we declare a Hashtable that consists of Integer type keys and String type values.
  • In lines 8 to 12, we use the Hashtable.put() method to insert values in the Hashtable.
  • In line 14, we display the original Hashtable.
  • In line 16, we use the HashTable.keys() method to create an empty enumeration to store the keys.
  • In line 17, we display a message regarding the enumeration of keys of the HashTable.
  • In lines 19 and 20, we use a while loop to display each key of the enumeration by checking if the enumeration had more elements in it or we reached the end to terminate the loop.

In this way, we can use the HashTable.keys() method to get the enumeration of the keys present in the HashTable.

RELATED TAGS

communitycreator
java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring