Write a Java program to get the subset of a TreeSet collection based on a specified range
This program demonstrates how to obtain a subset of a TreeSet in Java. Here's how the code works:
- The program starts by importing the necessary packages: java.io.* and java.util.* .
- The GetSubset class is defined.
- Inside the main method, a new TreeSet of integers named num is created and initialized with a few values.
- The subSet method is used to obtain a subset of num. This method takes two arguments: the starting value (inclusive) and the ending value (exclusive) of the subset. In this case, we're requesting a subset that includes all values between 20 (inclusive) and 35 (exclusive).
- The resulting subset is stored in a new TreeSet called subset.
- Finally, the original num and the resulting subset are printed to the console using System.out.println.
Source Code
import java.io.*;
import java.util.*;
public class GetSubset
{
public static void main(String args[])
{
TreeSet <Integer> num = new TreeSet <Integer>();
num.add(10);
num.add(35);
num.add(20);
num.add(45);
num.add(30);
num.add(25);
TreeSet <Integer> subset = (TreeSet <Integer> ) num.subSet(20, 35);
System.out.println("TreeSet Elements : " + num);
System.out.println("SubSet Elements : " + subset);
}
}
Output
TreeSet Elements : [10, 20, 25, 30, 35, 45]
SubSet Elements : [20, 25, 30]