Write a Java program to get the elements greater than and equal to the specified item from TreeSet Collection


This is a Java program that demonstrates how to use the tailSet() method of the TreeSet class to get a view of the subset of elements greater than or equal to a specified value.

The program first creates a TreeSet object called num, which is a collection of unique elements sorted in ascending order. It adds seven integers to the set using the add() method.

Then, the program creates a new TreeSet object called tailSet and assigns it the result of calling the tailSet(40) method on the num set. This returns a view of the subset of elements in the num set that are greater than or equal to 40.

Finally, the program prints the original num set and the tailSet view to the console using the println() method.

Source Code

import java.io.*;
import java.util.*;
public class GetElement_Greater
{
	public static void main(String args[])
	{
		TreeSet <Integer> num = new TreeSet <Integer>();
		num.add(45);
		num.add(30);
		num.add(50);
		num.add(25);
		num.add(60);
		num.add(35);
		num.add(80);
		TreeSet <Integer> tailSet = (TreeSet <Integer> ) num.tailSet(40);
 
		System.out.println("TreeSet Element : " + num);
		System.out.println("Tail Set : " + tailSet);
	}
}

Output

TreeSet Element : [25, 30, 35, 45, 50, 60, 80]
Tail Set : [45, 50, 60, 80]