import java.util.TreeSet;
public class AdvancedTreeSetExample {
public static void main(String[] args) {
// Create a TreeSet of integers
TreeSet<Integer> treeSet = new TreeSet<>();
// Add some elements to the TreeSet
treeSet.add(10);
treeSet.add(20);
treeSet.add(30);
treeSet.add(40);
treeSet.add(50);
// Print the TreeSet
System.out.println("TreeSet: " + treeSet);
// Get the greatest element in the TreeSet less than or equal to a given element
Integer floor30 = treeSet.floor(30);
System.out.println("Greatest element less than or equal to 30: " + floor30);
// Get the least element in the TreeSet greater than or equal to a given element
Integer ceiling35 = treeSet.ceiling(35);
System.out.println("Least element greater than or equal to 35: " + ceiling35);
// Remove and return the first (lowest) element in the TreeSet
Integer first = treeSet.pollFirst();
System.out.println("Removed first element: " + first);
// Remove and return the last (highest) element in the TreeSet
Integer last = treeSet.pollLast();
System.out.println("Removed last element: " + last);
// Print the TreeSet again
System.out.println("TreeSet after removing first and last elements: " + treeSet);
}
}
In this example, we create a new TreeSet
of integers and add some elements to it using the add()
method.
We then print the TreeSet
using the println()
method.
Next, we use the floor()
and ceiling()
methods to find the greatest element less than or equal to 30 and the least element greater than or equal to 35, respectively.
We then use the pollFirst()
and pollLast()
methods to remove and return the first (lowest) and last (highest) elements in the TreeSet
, respectively.
Finally, we print the TreeSet
again to see the elements that remain after removing the first and last elements.
The output of this code will be:
TreeSet: [10, 20, 30, 40, 50]
Greatest element less than or equal to 30: 30
Least element greater than or equal to 35: 40
Removed first element: 10
Removed last element: 50
TreeSet after removing first and last elements: [20, 30, 40]
This example demonstrates how to use some of the more advanced methods of the TreeSet
class, including floor()
, ceiling()
, pollFirst()
, and pollLast()
.