How to Get Sub Set from TreeSet in Java


In this example we will show how to get the sub Set from java TreeSet by giving specific range of values with subSet method of java TreeSet class.

Source Code

package com.beginner.examples;

import java.util.SortedSet;
import java.util.TreeSet;

public class GetSubSetFromTreeSet {

	public static void main(String[] args) {
		
		//create TreeSet.
		TreeSet treeSet = new TreeSet();
		
		treeSet.add("A");
		treeSet.add("B");
		treeSet.add("C");
		treeSet.add("D");
		
		/*
		 * To get the sub Set from Java TreeSet use subSet method of TreeSet.
		 */
		SortedSet sortedSet = treeSet.subSet("B","D");
		
		System.out.println("SortedSet Contains : " + sortedSet);
		

	}

}

Output:

SortedSet Contains : [B, C]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments