How to check if a specific key is present in a Hashtable or not?
How to Check if a Specific Key is Present in a Hashtable in Java
In Java, you can use the Hashtable
class from the java.util
package to store key-value pairs. To check if a specific key is present in a Hashtable
, you can use the containsKey()
method. This method returns true
if the key is present in the hashtable and false
otherwise.
Example Implementation
Here’s an example to demonstrate how to check if a specific key is present in a Hashtable
:
import java.util.Hashtable; public class Main { public static void main(String[] args) { // Creating a Hashtable Hashtable<String, Integer> hashtable = new Hashtable<>(); // Adding key-value pairs to the Hashtable hashtable.put("One", 1); hashtable.put("Two", 2); hashtable.put("Three", 3); // Checking if a specific key is present String keyToCheck = "Two"; if (hashtable.containsKey(keyToCheck)) { System.out.println("Key \"" + keyToCheck + "\" is present in the hashtable."); } else { System.out.println("Key \"" + keyToCheck + "\" is not present in the hashtable."); } // Checking for a key that is not present keyToCheck = "Four"; if (hashtable.containsKey(keyToCheck)) { System.out.println("Key \"" + keyToCheck + "\" is present in the hashtable."); } else { System.out.println("Key \"" + keyToCheck + "\" is not present in the hashtable."); } } }
Explanation
-
Creating a Hashtable:
- We create an instance of
Hashtable
to store key-value pairs.
- We create an instance of
-
Adding Key-Value Pairs:
- We use the
put()
method to add key-value pairs to the hashtable.
- We use the
-
Checking for Key Presence:
- We use the
containsKey()
method to check if a specific key is present in the hashtable. - If the key is present,
containsKey()
returnstrue
; otherwise, it returnsfalse
.
- We use the
Output
Key "Two" is present in the hashtable.
Key "Four" is not present in the hashtable.
Summary
- Hashtable: A data structure that stores key-value pairs.
- containsKey() Method: Used to check if a specific key is present in the hashtable.
- Usage:
- Returns
true
if the key is present. - Returns
false
if the key is not present.
- Returns
This method is straightforward and efficient for checking the presence of keys in a Hashtable
. For more in-depth knowledge and practical examples on Java data structures and other programming concepts, consider exploring Grokking the Coding Interview on DesignGurus.io, which provides comprehensive courses on essential coding and interview techniques.
GET YOUR FREE
Coding Questions Catalog