Java Utility Library

Java WeakHashMap - containsKey() Method



The java.util.WeakHashMap.containsKey() method returns true if this map contains a mapping for the specified key.

Syntax

public boolean containsKey(Object key)

Parameters

key Specify the key whose presence in this map is to be tested.

Return Value

Returns true if there is a mapping for key; false otherwise.

Exception

NA.

Example:

In the example below, the java.util.WeakHashMap.containsKey() method is used to check the presence of specified key in the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a weakhashmap
    WeakHashMap<Integer, String> MyMap = new WeakHashMap<Integer, String>();

    //populating MyMap
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");

    //check the presence of 103 key
    System.out.print("Does MyMap contain 103 key? - ");  
    System.out.print(MyMap.containsKey(103));  
    
    //check the presence of 105 key
    System.out.print("\nDoes MyMap contain 105 key? - ");  
    System.out.print(MyMap.containsKey(105));  
  }
}

The output of the above code will be:

Does MyMap contain 103 key? - true
Does MyMap contain 105 key? - false

❮ Java.util - WeakHashMap