What is the WeakHashMap.containsValue method in Java?

WeakHashMap is a kind of Map implemented based on the HashTable. The WeakHashMap only stores WeakReference type 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 WeakHashMap class.

  • In line 4, we created a WeakHashMap object with the name map.

  • In lines 5 and 6, we used the put method to add two mappings ({1=one, 2=two}) to the map object.

  • In line 7, we used the containsValue method to check if the map has a key mapping for the value "one". true is returned as a result because the key 1 is mapped to the value "one".

  • In line 8, we used the containsValue method to check if the map has a key mapping for the value "three". false is returned as a result because the no key is mapped to the value "three".

Free Resources