Tuesday 3 June 2014

HashMap : containsKey(Object key) : Search for a key in HashMap

containsKey(Object key)
Returns true if this map contains a mapping for the specified key.

import java.util.*;

class HashMapContainsKey{
  public static void main(String args[]){
    HashMap<Integer, String> myMap1 = new HashMap<> ();
  
  /* Add data to the myMap1 */
  myMap1.put(1, "First");
  myMap1.put(2, "Second");
  myMap1.put(3, "Third");
  myMap1.put(4, "Fourth");
  
  System.out.println("Data in myMap1 is");
  System.out.println(myMap1);
  
  System.out.print("\nIs myMap1 contains key 1 ");
  System.out.println(myMap1.containsKey(1));
  
  System.out.print("Is myMap1 contains key 10 ");
  System.out.println(myMap1.containsKey(10));
  }
}


Output
Data in myMap1 is
{1=First, 2=Second, 3=Third, 4=Fourth}

Is myMap1 contains key 1 true
Is myMap1 contains key 10 false

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment