TreeSet subSet() method in java

Let’s learn TreeSet subSet() method in java.

TreeSet subSet() method in java

subSet() method of TreeSet class returns a view of the portion of this set whose elements range from fromElement to toElement.

Syntax:

public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)


Parameters:

fromElement low endpoint of the returned set.

fromInclusive true if the low endpoint is to be included in the returned view.

toElement high endpoint of the returned set.

toInclusive true if the high endpoint is to be included in the returned view.

Throws:

ClassCastException – if fromElement and toElement cannot be compared to one another using this set’s comparator.

NullPointerException – if fromElement or toElement is null and this set uses natural ordering, or its comparator does not permit null elements.

IllegalArgumentException – if fromElement is greater than toElement; or if this set itself has a restricted range, and fromElement or toElement lies outside the bounds of the range.

Also read – TreeSet in java

Now let’s see example on TreeSet subSet() method.

import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetSubSetMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      TreeSet<Integer> sub = new TreeSet<Integer>();
      ts.add(11);
      ts.add(22);
      ts.add(33);
      ts.add(44);
      ts.add(55);
      ts.add(66);
      ts.add(77);
      ts.add(88);
      // creating subset
      sub = (TreeSet)ts.subSet(22, true, 77, true);
      // create iterator
      Iterator<Integer> iterate = sub.iterator();
      System.out.println("TreeSet subset: ");
      while(iterate.hasNext())
      {
         System.out.println(iterate.next() + " ");
      }
   }
}


Output:

TreeSet subset:
22
33
44
55
66
77