What is the WeakHashMap.containsValue method in Java?
WeakHashMapis a kind ofMapimplemented based on theHashTable. TheWeakHashMaponly storesWeakReferencetype as their keys. Once the key is no longer used, the respective mapping will be automatically removed when the garbage collection is done.
The containsValue method of WeakHashMap is used to check if the specified value is present in the WeakHashMap object.
Syntax
public boolean containsValue(Object value)
Parameter
The value to be checked as present is passed as an argument.
Return value
This method returns true if the value has one or more keys mapping. Otherwise, false is returned.
Code
The below example shows how to use the containsValue method.
import java.util.WeakHashMap;class WeakHashMapContainsValueExample {public static void main( String args[] ) {WeakHashMap<Integer, String> map = new WeakHashMap<>();map.put(1, "one");map.put(2, "two");System.out.println("\nChecking if the value 'one' is present : "+ map.containsValue("one"));System.out.println("\nChecking if the value 'three' is present : "+ map.containsValue("three"));}}
Explanation
In the above code:
-
In line 1, we imported the
WeakHashMapclass. -
In line 4, we created a
WeakHashMapobject with the namemap. -
In lines 5 and 6, we used the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
In line 7, we used the
containsValuemethod to check if themaphas a key mapping for the value"one".trueis returned as a result because the key1is mapped to the value"one". -
In line 8, we used the
containsValuemethod to check if themaphas a key mapping for the value"three".falseis returned as a result because the no key is mapped to the value"three".