What is the TreeSet.subSet() function in Java?

In this shot, we will discuss how to use the TreeSet.subSet() method in Java.

The TreeSet.subSet() method is present in the TreeSet class inside the java.util package. It obtains the subset of the TreeSet in the specified range.

Parameter

TreeSet.subSet() method takes the below mentioned parameters:

  • Lower: The lower limit of the range of the elements’ value which can be included to obtain the subset of the TreeSet.
  • Upper: The upper limit of the range of the elements’ value which should be excluded to obtain the subset of the TreeSet.

Return

  • Subset: It returns the subset of the TreeSet between the specified range.

Example

  • We have a TreeSet that is [1,3,5,8,9]

  • It has the range 3 to 9

The lower limit of the range of elements can be included but the upper limit should be excluded.

The subset should be 3,5,8.

So the result of the TreeSet.subSet() method is 3,5,8.

Code

Let’s look at the code snippet below:

import java.io.*;
import java.util.*;
class Main
{
public static void main(String args[])
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
tree_set.add(1);
tree_set.add(8);
tree_set.add(5);
tree_set.add(3);
tree_set.add(0);
tree_set.add(22);
tree_set.add(10);
System.out.println("TreeSet: " + tree_set);
TreeSet<Integer> subset = new TreeSet<Integer>();
subset = (TreeSet<Integer>)tree_set.subSet(1,9);
Iterator i;
i=subset.iterator();
System.out.print("The resultant values within the subset: ");
while (i.hasNext())
System.out.print(i.next() + " ");
}
}

Explanation

  • In lines 1 and 2, we imported the required packages.
  • In line 4, we made a Main class.
  • In line 6, we made a main function.
  • In line 8, we declared a TreeSet of Integer type.
  • *In lines 9 to 15, we added the elements into the TreeSet by using the TreeSet.add() method.
  • In line 16, we displayed the original TreeSet with a message.
  • In line 18, we declared another TreeSet to store the subset.
  • In line 19, we called the TreeSet.subset() method for a range and stored the subset in another TreeSet declared in line 18.
  • In line 21, we made an object of the Iterator class.
  • In line 22, we iterated and assigned the subset TreeSet to the Iterator object.
  • In line 24, we displayed the message regarding the subset.
  • In lines 25 and 26, we used a while loop to traverse over the subset using the Iterator object TreeSet and displayed the elements of the subset.

In this way, we can use the TreeSet.subSet() method to obtain the subset in a specified range of a TreeSet.

Free Resources