Here this example will use subMap method of Java TreeMap class to get the sub Map from Treemap by giving specific range of keys.
Source Code
package com.beginner.examples;
import java.util.SortedMap;
import java.util.TreeMap;
public class GetSubMapFromTreeMap {
public static void main(String[] args) {
//create TreeMap.
TreeMap treeMap = new TreeMap();
treeMap.put("1","Alice");
treeMap.put("2","Bob");
treeMap.put("3","Jack");
/*
* To get the sub Map from Java TreeMap useing subMap method of TreeMap.
*/
SortedMap sortedMap = treeMap.subMap("2","4");
System.out.println("SortedMap Contains : " + sortedMap);
}
}
Output:
SortedMap Contains : {2=Bob, 3=Jack}
References
Imported packages in Java documentation: