How to Obtain Sub Map from Java TreeMap


This article will explain how to get sub Map from TreeMap whose keys are grater than or equal to the specified key with tailMap method of java TreeMap class.

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:

Tail Map Contains : {2=Bob, 3=Jack}

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments