Wednesday 8 August 2012

Get Size of Java TreeMap Example


This Java Example shows how to get the size or nubmer of key value pairs stored in TreeMap using size method.

import java.util.TreeMap;

public class GetSizeOfTreeMapExample {

 public static void main(String[] args) {

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

  /**
   * To get the size of TreeMap use int size() method
   * of TreeMap class.It returns the number of key 
   * value pairs stored in TreeMap object.
   **/
  System.out.println("Size of TreeMap : " + tMap.size());

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

  System.out.println("Size of TreeMap after addition : " + tMap.size());

  // remove one element from TreeMap using remove method
  Object obj = tMap.remove("2");

  System.out.println("Size of TreeMap after removal : " + tMap.size());
 }
}


The output is:


Size of TreeMap : 0
Size of TreeMap after addition : 3
Size of TreeMap after removal : 2

No comments:

Post a Comment