What is the HashTable.containsValue() method in Java?
HashTable.containsValue() is a method present in the HashTable class inside the java.util package.
The HashTable.containsValue() method is used to check if the particular value is being mapped by any of the keys present in the HashTable.
Syntax
HashTable.containsValue(Object Value)
Parameters
The HashTable.containsValue() method takes one parameter:
Value: The value which needs to be checked to see whether or not it is mapped by any keys in theHashTable.
Return value
HashTable.containsValue() returns a boolean value:
-
true: If the value is mapped by any key present in theHashTable. -
false: If the value is not mapped by any key present in theHashTable.
Code
Let’s see the below code snippet to better understand this.
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.contains()");h1.put(27, "method");h1.put(9, "in java.");System.out.println("The value=method is present in Hashtable?: "+h1.containsValue("method"));System.out.println("The value=in java. is present in Hashtable?: "+h1.containsValue("in java."));System.out.println("The value=hello is present in Hashtable?: "+h1.containsValue("hello"));}}
Explanation
- In line 1, we import the required package.
- In line 2, we make a
Mainclass. - In line 4, we make a
mainfunction. - In line 6, we declare a
Hashtableconsisting ofIntegertype keys andStringtype values. - In lines 8 to 12, we insert values in the
Hashtableby using theHashtable.put()method. - In lines 14 to 16, we display whether the value passed as argument is mapped with any keys present in the
HashTableor not with a message.
In this way, we can use the HashTable.containsValue() method to check if the particular value is being mapped by any of the keys present in the HashTable.