Grokking Modern System Design Interview for Engineers & Managers
Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.
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.
TreeSet.subSet()
method takes the below mentioned parameters:
TreeSet
.TreeSet
.TreeSet
between the specified range.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
.
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() + " "); } }
Main
class.main
function.TreeSet
of Integer
type.TreeSet
by using the TreeSet.add()
method.TreeSet
with a message.TreeSet
to store the subset.TreeSet.subset()
method for a range and stored the subset in another TreeSet
declared in line 18.Iterator
class.TreeSet
to the Iterator object.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
.
RELATED TAGS
CONTRIBUTOR
Grokking Modern System Design Interview for Engineers & Managers
Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.