Java Program to get Sub Map from TreeMap

Java 8Object Oriented ProgrammingProgramming

To get Sub Map from TreeMap, let us first create a TreeMap and set key-value pair −

TreeMap<String, String>tMap = new TreeMap<String, String>();
tMap.put("1", "A");
tMap.put("2", "B");
tMap.put("3", "C");
tMap.put("4", "D");
tMap.put("5", "E");
tMap.put("6", "F");
tMap.put("7", "G");

Now, let’s say you need to get submap from 3 to 7. For that, use the method submap() as −

=SortedMap<String, String>map = tMap.subMap("3", "7");

Example

 Live Demo

import java.util.SortedMap;
import java.util.TreeMap;
public class Demo {
   public static void main(String[] args) {
      TreeMap<String, String>tMap = new TreeMap<String, String>();
      tMap.put("1", "A");
      tMap.put("2", "B");
      tMap.put("3", "C");
      tMap.put("4", "D");
      tMap.put("5", "E");
      tMap.put("6", "F");
      tMap.put("7", "G");
      tMap.put("8", "H");
      tMap.put("9", "I");
      tMap.put("10", "J");
      SortedMap<String, String>map = tMap.subMap("3", "7");
      System.out.println("SortedMap = " + map);
      map = tMap.subMap("5", "7");
      System.out.println("SortedMap = " + map);
      map = tMap.subMap("8", "8");
      System.out.println("SortedMap = " + map);
   }
}

Output

SortedMap= {3=C, 4=D, 5=E, 6=F}
SortedMap = {5=E, 6=F}
SortedMap = {}
raja
Published on 25-Apr-2019 13:07:22
Advertisements