Tuesday 7 August 2012

Simple Java TreeMap example


This simple Java Example shows how to use Java TreeMap. It also describes how to add something to  TreeMap and how to retrieve the value added from  TreeMap .



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

public class JavaTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap
  TreeMap phoneBook = new TreeMap();

  /**
   * Add key value pair to TreeMap using Object put(Object key, Object
   * value) method of Java TreeMap 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");

  // retrieve value using Object get(Object key) method of Java TreeMap
  // class
  Object phoneNo = phoneBook.get("Joy");
  System.out.println("Phone number of Joy: " + phoneNo);

  System.out.println("The Map contains...");

  /**
   * Set keySet() - Returns a Set view of the keys contained in this map.
   * The set's iterator will return the keys in ascending order. The map
   * is backed by this TreeMap instance, so changes to this map are
   * reflected in the Set, and vice-versa.
   **/

  Set nameSet = phoneBook.keySet();
  for (Object name : nameSet) {
   System.out.println("Name: " + name + " Phone: "
     + phoneBook.get(name));
  }

  /**
   * put - If the map previously contained a mapping for this key, the old
   * value is replaced and the put method returns the old value.
   **/

  Object oldPhone = phoneBook.put("Roy", "222222");

  System.out.println("Roy's old phone number:" + oldPhone);
  System.out.println("Roy's new phone number:" + phoneBook.get("Roy"));

 }
}


The output is:


Phone number of Joy: 245786
The Map contains...
Name: John Phone: 245745
Name: Joy Phone: 245786
Name: Roy Phone: 233783
Roy's old phone number:233783
Roy's new phone number:222222

No comments:

Post a Comment