import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// Create a TreeSet of strings
TreeSet<String> treeSet = new TreeSet<>();
// Add some elements to the TreeSet
treeSet.add("apple");
treeSet.add("banana");
treeSet.add("cherry");
treeSet.add("date");
// Print the TreeSet
System.out.println("TreeSet: " + treeSet);
// Check if an element is in the TreeSet
boolean containsCherry = treeSet.contains("cherry");
System.out.println("Contains cherry? " + containsCherry);
// Remove an element from the TreeSet
treeSet.remove("banana");
System.out.println("TreeSet after removing banana: " + treeSet);
// Get the first and last elements in the TreeSet
String first = treeSet.first();
String last = treeSet.last();
System.out.println("First element: " + first);
System.out.println("Last element: " + last);
}
}
In this example, we first import the TreeSet
class from the java.util
package. We then create a new TreeSet
of strings and add some elements to it using the add()
method.
We then print the TreeSet
using the println()
method, which will print the elements in the TreeSet
in sorted order, since TreeSet
maintains its elements in sorted order.
Next, we check if an element is in the TreeSet
using the contains()
method, and remove an element from the TreeSet
using the remove()
method.
Finally, we get the first and last elements in the TreeSet
using the first()
and last()
methods, respectively.
The output of this code will be:
TreeSet: [apple, banana, cherry, date]
Contains cherry? true
TreeSet after removing banana: [apple, cherry, date]
First element: apple
Last element: date
This example demonstrates how to create a TreeSet
, add and remove elements from it, and get the first and last elements in the TreeSet
. It also shows how the TreeSet
maintains its elements in sorted order.