java.util.HashMap.containsKey() Method


Description

The containsKey(Object key) method is used to check if this map contains a mapping for the specified key.

Declaration

Following is the declaration for java.util.HashMap.containsKey() method.

public boolean containsKey(Object key)

Parameters

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

Return Value

The method call returns 'true' if this map contains a mapping for the specified key.

Exception

NA

Example

The following example shows the usage of java.util.HashMap.containsKey()

package com.tutorialspoint;

import java.util.*;

public class HashMapDemo {
   public static void main(String args[]) {
      
      // create hash map
      HashMap newmap = new HashMap();

      // populate hash map
      newmap.put(1, "tutorials");
      newmap.put(2, "point");
      newmap.put(3, "is best"); 

      // check existence of key 2
      System.out.println("Check if key 2 exists: " + newmap.containsKey(2));
   }    
}

Let us compile and run the above program, this will produce the following result.

Check if key 2 exists: true
java_util_hashmap.htm
Advertisements