Tuesday 31 July 2012

Check if a particular key exists in Java HashMap example


This Java Example shows how to check if HashMap object contains a particular key using containsKey method of HashMap class.


import java.util.HashMap;

public class CheckParticularKeyExistHashMapExample {

 public static void main(String[] args) {

  // create object of HashMap

  HashMap phoneBook = new HashMap();

  /**
   * Add key value pair to HashMap using Object put(Object key, Object
   * value) method of Java HashMap class, where key and value both are
   * objects put method returns Object which is either the value
   * previously tied to the key or null if no value mapped to the key.
   **/

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * To check whether a particular key exists in HashMap use boolean
   * containsKey(Object key) method of HashMap class. It returns true if
   * the HashMap contains mapping for specified key otherwise false.
   **/

  boolean blnExists = phoneBook.containsKey("Joy");
  System.out.println("Name 'Joy' exists in HashMap ? : " + blnExists);

 }
}


The output is:


Name 'Joy' exists in HashMap ? : true

No comments:

Post a Comment