Hashtable

Check value existence in Hashtable example

In this example we shall show you how to check a value existence in a Hashtable. The Hashtable API provides methods for such operations. To check if a value exists in a Hashtable one should perform the following steps:

  • Create a new Hashtable.
  • Populate the hashtable with elements, using put(K key, V value) API method of Hashtable.
  • Invoke containsValue(Object value) API method of Hashtable, with a specific value as parameter. The method returns true if this hashtable maps one or more keys to this value and false otherwise,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
 
import java.util.Hashtable;
 
public class CheckValueHashtable {
 
  public static void main(String[] args) {
 
    // Create a Hashtable and populate it with elements
    Hashtable hashtable = new Hashtable();
    hashtable.put("key_1","value_1");
    hashtable.put("key_2","value_2");
    hashtable.put("key_3","value_3");
 
    // boolean containsKey(Object key) returns true if the Hashtable contains the key, otherwise false.
    boolean exists = hashtable.containsValue("value_2");
    System.out.println("value_2 exists in Hashtable ? : " + exists);

  }
}

Output:

value_2 exists in Hashtable ? : true

 
This was an example of how to check a value existence in a Hashtable in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button