Thursday 9 August 2012

Get Sub Map from Java TreeMap example


This Java Example shows how to get the sub Map from Java Treemap by giving specific
range of keys using
subMap method of Java TreeMap class.

SortedMap subMap(Object fromKey,Object toKey)


Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. (If fromKey and toKey are equal, the returned sorted map is empty.) The returned sorted map is backed by this map, so changes in the returned sorted map are reflected in this map, and vice-versa. The returned sorted map supports all optional map operations.

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key less than fromKey or greater than or equal to toKey.

See the example given below:

import java.util.TreeMap;
import java.util.SortedMap;

public class GetSubMapFromTreeMapExample {

 public static void main(String[] args) {

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

  // add key value pairs to TreeMap
  
  treeMap.put("1", "One");
  treeMap.put("3", "Three");
  treeMap.put("2", "Two");
  treeMap.put("5", "Five");
  treeMap.put("4", "Four");

  /**
   * To get the sub Map from Java TreeMap use,
   * SortedMap subMap(Object fromKey,Object toKey)
   * method of TreeMap class.
   **/

  SortedMap sortedMap = treeMap.subMap("2", "5");

  System.out.println("SortedMap Contains : " + sortedMap);

 }
}


The output is:


SortedMap Contains : {2=Two, 3=Three, 4=Four}

No comments:

Post a Comment