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
TreeSetbetween the specified range.
Example
-
We have a
TreeSetthat is[1,3,5,8,9] -
It has the range
3to9
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
Mainclass. - In line 6, we made a
mainfunction. - In line 8, we declared a
TreeSetofIntegertype. - *In lines 9 to 15, we added the elements into the
TreeSetby using theTreeSet.add()method. - In line 16, we displayed the original
TreeSetwith a message. - In line 18, we declared another
TreeSetto store the subset. - In line 19, we called the
TreeSet.subset()method for a range and stored the subset in anotherTreeSetdeclared in line 18. - In line 21, we made an object of the
Iteratorclass. - In line 22, we iterated and assigned the subset
TreeSetto the Iterator object. - In line 24, we displayed the message regarding the subset.
- In lines 25 and 26, we used a
whileloop to traverse over the subset using theIteratorobjectTreeSetand 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.