containsKey(Object key) method of Map Interface in Java.

containsKey(Object key) method of Map Interface in Java.


Posted in : Core Java Posted on : February 18, 2011 at 7:36 PM Comments : [ 0 ]

In this method a specified 'key' is to be tested whether, it is present into the set of keys/'key-value' set or, not.

containsKey(Object key) method of Map Interface in Java.

In this section we will discuss how can containsKey(Object key) method be implemented in Map interface in java.

Syntax

boolean containsKey(Object key)

This method checks for the specified key whether the underlying map contains.

In this method a specified 'key' is to be tested whether, it is present into the set of keys/'key-value' set or, not. It returns 'true' if and only if a specified key does exist into the key-value mappings of the underlying map otherwise 'false'.   

Parameter description

key : It takes key from the (key-value) mappings that you want to do test for its presence. 

Example of containsKey(Object key) method

In this example we will show you how does containsKey(Object key) method work in Map interface. This example will help you to understand how you can test the presence of a specified key. In the following example we will also show you what does this method return when the underlying map may or may not contains the specified key.

Example :

package devmanuals.com;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
public class MapContainsKey {
  public static void main(String args[]){
    Map mp =new HashMap();
    mp.put(1"A");
    mp.put(2"B");
    mp.put(3"C");
    mp.put(4"D");
    System.out.println("Mappings are : "+mp);
    Set st= mp.keySet();
    System.out.println("Set of keys are : "+st);
    boolean bol= mp.containsKey(4);
    System.out.println("does 4 exist in set of keys : "+bol);
    boolean bol1=mp.containsKey(5);
    System.out.println("does 5 exist in set of keys : "+bol1);
  }
}

Output :

Mappings are : {1=A, 2=B, 3=C, 4=D}

Set of keys are : [1, 2, 3, 4]

does 4 exist in set of keys : true

does 5 exist in set of keys : false

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics