Sunday 29 July 2012

Get Sub Set from Java TreeSet example


This Java Example shows how to get the sub Set from Java TreeSet by giving specific range of values using subSet method of Java TreeSet class.

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

public class GetSubSetFromTreeSetExample {

	public static void main(String[] args) {

		// create TreeSet object
		TreeSet tSet = new TreeSet();

		// add elements to TreeSet
		tSet.add("1");
		tSet.add("3");
		tSet.add("2");
		tSet.add("5");
		tSet.add("4");

		/**
		 * To get the sub Set from Java TreeSet use, SortedSet subSet(Object
		 * fromElement,Object toElement) method of TreeSet class.
		 * 
		 * This method returns portion of the TreeSet whose elements range from
		 * from (inclusive) to to(exclusive).
		 * 
		 * Please note that, the SortedSet returned by this method is backed by
		 * the original TreeSet. So any changes made to SortedSet will be
		 * reflected back to original TreeSet.
		 **/

		SortedSet sortedSet = tSet.subSet("2", "5");

		System.out.println("Subset Contains : " + sortedSet);

	}
}


The output is:


Subset Contains : [2, 3, 4]

No comments:

Post a Comment