Tuesday 7 August 2012

Get Set view of Keys from Java TreeMap example


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


import java.util.Set;
import java.util.TreeMap;

public class GetSetViewOfKeysFromTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap

  TreeMap phoneBook = new TreeMap();

  // Add key value pairs to TreeMap.

  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 in ascending order.
   **/

  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 TreeMap. Any key that is removed from Set will
   * also be removed from original TreeMap object. The same
   * is not the case with the element addition.
   **/

  // remove Roy from nameSet

  nameSet.remove("Roy");

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


The output is:


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

No comments:

Post a Comment