Monday 30 July 2012

Get Set view of Keys from Java HashMap example


This Java Example shows how to get a Set of keys contained in HashMap using keySet method of Java HashMap class.


import java.util.Iterator;
import java.util.HashMap;
import java.util.Set;

public class GetSetViewOfKeysFromHashMapExample {

 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");

  /**
   * Set keySet() - Returns a set view of the keys contained in this map.
   **/

  Set nameSet = phoneBook.keySet();

  System.out.println("Names in the phone book are :");

  for (Object name : nameSet) {
   System.out.println("Name: " + name);
  }

  /**
   * Please note that resultant Set object is backed by the HashMap. Any
   * key that is removed from Set will also be removed from original
   * HashMap object. The same is not the case with the element addition.
   **/

  // remove Roy from nameSet

  nameSet.remove("Roy");

  // check if original HashMap still contains entry for name Roy.
  boolean blnExists = phoneBook.containsKey("Roy");
  System.out.println("Does HashMap contain Roy ? " + blnExists);
 }
}


The output is:


Names in the phone book are :
Name: Roy
Name: Joy
Name: John
Does HashMap contain Roy ? false

No comments:

Post a Comment