TreeSet subSet() method in java

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

TreeSet subSet() method in java

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

Syntax:

public SortedSet<E> subSet(E fromElement, E toElement)

Parameters:

fromElement low endpoint (inclusive) of the returned set.

toElement high endpoint (exclusive) of the returned set.

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(E fromElement, E toElement) method.

import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetSubSetFromElementMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      TreeSet<Integer> sub = new TreeSet<Integer>();
      ts.add(11);
      ts.add(21);
      ts.add(31);
      ts.add(41);
      ts.add(51);
      ts.add(61);
      ts.add(71);
      ts.add(81);
      // create subSet
      sub = (TreeSet)ts.subSet(31, 71);
      // create iterator
      Iterator<Integer> iterate = sub.iterator();
      System.out.println("TreeSet subset: ");
      while(iterate.hasNext())
      {
         System.out.println(iterate.next() + " ");
      }
   }
}


Output:

TreeSet subset:
31
41
51
61

1 Comment

Comments are closed.