How to use WeakHashMap.containsKey() 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 containsKey() method of WeakHashMap is used to check if a value is mapped to the specified key.

Syntax

public boolean containsKey(Object key)

Parameters

The key to check for presence is passed as a parameter.

Return value

This method returns true if the key has a mapping. Otherwise, false is returned.

Code

The example below shows how to use the containsKey() method.

import java.util.WeakHashMap;
class ContainsKeyExample {
public static void main( String args[] ) {
// create a WeakHashMap object which can have string key and integer value
WeakHashMap<String, Integer> map = new WeakHashMap<>();
String key = "ten";
//add a new entry to the map
map.put(key, 10);
//print the map
System.out.println("The map is : " + map);
//check of the map contains key
System.out.println("Checking if the key 'ten' has mapping: "+ map.containsKey(key));
System.out.println("Checking if the key 'one' has mapping: "+ map.containsKey("one"));
}
}

Explanation

In the code above,

  • In line 1: Import the WeakHashMap class.

  • In line 5: Create a WeakHashMap object with the name map.

  • In line 6: Create a String object with the name key and value ten.

  • In line 8: Used the put method to add one mapping ({ten=10}) to the map object.

  • In line 12: Use the containsKey method to check if the map has a mapping for the key ten. true is returned as a result because the map has a mapping for the key ten.

  • In line 13: Use the containsKey method to check if the map has a mapping for the key one. false is returned as a result because the map has a mapping for the key one.