Java - How to Get a Sublist of TreeMap

  In the example below we will see how to get from a TreeMap a new sub-TreeMap sorted using the subMap() of the TreeMap.

subMap(K fromKey, K toKey)

Example:

import java.util.*; 

class TreeMapSub {

public static void main(String args[]) {

TreeMap treemap = new TreeMap();

// elements
treemap.put("a", "e4");
treemap.put("b", "e5");
treemap.put("c", "e1");
treemap.put("d", "e3");
treemap.put("e", "e2");

System.out.println("Before:");

/* browse the unsorted TreeMap with Iterator */

Set set = treemap.entrySet();
Iterator i = set.iterator();
// Show elements
while(i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
System.out.print(entry.getKey() + " : ");
System.out.println(entry.getValue());
}

System.out.println("After:");

// call the subMap()
SortedMap subM = treemap.subMap("a","d");

/* browse the submap with Iterator */

set = subM.entrySet();
i = set.iterator();
// Show elements
while(i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
System.out.print(entry.getKey() + " : ");
System.out.println(entry.getValue());
}

}
}

Runtime

Front:
a: e4
b: e5
c: e1
d: e3
e: e2
After:
a: e4
b: e5
c: e1

References
java.util.TreeMap.subMap() Method