Java TreeMap subMap(K fromKey,K toKey) Method Example

The subMap(K fromKey, K toKey) method of java.util.TreeMap class returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.

Signature

public SortedMap<K,V> subMap(K fromKey,K toKey)

This method returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.

Example

The following example shows the usage of java.util.TreeMap.subMap(fromKey,toKey) method.

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

public class SubMapMethodTreeMapExample 
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String>  treeMap1 = new TreeMap<Integer,String>();
        SortedMap<Integer, String>  subMap = new TreeMap<Integer,String>();
        
        // use put() method to put elements to the TreeMap
        treeMap1.put(1,"Element1");
        treeMap1.put(2,"Element2");
        treeMap1.put(3,"Element3");
        treeMap1.put(4,"Element4");
        treeMap1.put(5,"Element5");
        
        //Print the elements of TreeMap 
        System.out.println("**Elements of TreeMap**");
        for(Map.Entry<Integer,String> entry : treeMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" ...."+"Value : "+entry.getValue());
        }
        //Print the Size of the treemap
        System.out.println("**Size of the treemap is : "+treeMap1.size()+"**");
        
        //Get the subMap from treeMap1
        subMap = treeMap1.subMap(1, 3);
        
        //Print the elements of SubMap
        System.out.println("**Elements of SubMap**");
        for(Map.Entry<Integer,String> entry : subMap.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" ...."+"Value : "+entry.getValue());
        }
        //Print the Size of the submap
        System.out.println("**Size of the submap is : "+subMap.size()+"**");
     }
}

Output

**Elements of TreeMap**
Key : 1 ....Value : Element1
Key : 2 ....Value : Element2
Key : 3 ....Value : Element3
Key : 4 ....Value : Element4
Key : 5 ....Value : Element5
**Size of the treemap is : 5**
**Elements of SubMap**
Key : 1 ....Value : Element1
Key : 2 ....Value : Element2
**Size of the submap is : 2**

Leave a Reply

Your email address will not be published. Required fields are marked *