Wednesday 8 August 2012

Remove value from Java TreeMap example


This Java Example shows how to remove a key value pair from TreeMap object using remove method.

import java.util.TreeMap;

public class RemoveValueFromTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap tMap = new TreeMap();

  // add key value pairs to TreeMap
  tMap.put("1", "One");
  tMap.put("2", "Two");
  tMap.put("3", "Three");

  /**
   * To remove a key value pair from TreeMap use Object
   * remove(Object key) method of TreeMap class.It returns
   * either the value mapped with the key or null if no
   * value was mapped.
   **/

  Object obj = tMap.remove("2");
  System.out.println(obj + " Removed from TreeMap");

 }
}


The output is:


Two Removed from TreeMap

No comments:

Post a Comment