Skip to Content

Get Sub Set from Java TreeSet example

  1. /*
  2.   Get Sub Set from Java TreeSet example
  3.   This Java Example shows how to get the sub Set from Java TreeSet by giving specific
  4.   range of values using subSet method of Java TreeSet class.
  5. */
  6.  
  7. import java.util.TreeSet;
  8. import java.util.SortedSet;
  9.  
  10. public class GetSubSetFromTreeSetExample {
  11.  
  12.   public static void main(String[] args) {
  13.  
  14.     //create TreeSet object
  15.     TreeSet tSet = new TreeSet();
  16.    
  17.     //add elements to TreeSet
  18.     tSet.add("1");
  19.     tSet.add("3");
  20.     tSet.add("2");
  21.     tSet.add("5");
  22.     tSet.add("4");
  23.  
  24.    
  25.     /*
  26.       To get the sub Set from Java TreeSet use,
  27.       SortedSet subSet(int from, int to) method of TreeSet class.
  28.      
  29.       This method returns portion of the TreeSet whose elements range from
  30.       from (inclusive) to to(exclusive).
  31.      
  32.       Please note that, the SortedSet returned by this method is backed by
  33.       the original TreeSet. So any changes made to SortedSet will be
  34.       reflected back to original TreeSet.
  35.     */
  36.    
  37.     SortedSet sortedSet = tSet.subSet("2","5");
  38.    
  39.     System.out.println("SortedSet Contains : " + sortedSet);
  40.    
  41.    
  42.   }
  43. }
  44.  
  45. /*
  46. Output would be
  47. SortedSet Contains : [2, 3, 4]
  48. */

Advertisement: