Curriculum
In Java, TreeSet
is a class that implements the SortedSet
interface using a tree-based data structure. The elements in a TreeSet
are stored in sorted order, and the implementation provides efficient methods for finding, adding, removing, and iterating over the elements in the set.
Here’s an example of how to create a TreeSet
and add elements to it:
import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { // Create a TreeSet TreeSet<Integer> numbers = new TreeSet<Integer>(); // Add some elements numbers.add(5); numbers.add(2); numbers.add(8); numbers.add(1); numbers.add(10); // Print the TreeSet System.out.println(numbers); } }
Output
[1, 2, 5, 8, 10]
As you can see, the elements in the TreeSet
are automatically sorted in ascending order.
TreeSet
provides several methods that are useful for working with sorted sets of data. Here are some of the most commonly used methods:
add(E element)
: Adds an element to the set.clear()
: Removes all elements from the set.contains(Object obj)
: Returns true if the set contains the specified element.first()
: Returns the first (lowest) element in the set.last()
: Returns the last (highest) element in the set.remove(Object obj)
: Removes the specified element from the set.size()
: Returns the number of elements in the set.In addition to these basic methods, TreeSet
also provides methods for navigating the set in various ways, such as:
ceiling(E element)
: Returns the least element in the set greater than or equal to the given element, or null if there is no such element.floor(E element)
: Returns the greatest element in the set less than or equal to the given element, or null if there is no such element.higher(E element)
: Returns the least element in the set strictly greater than the given element, or null if there is no such element.lower(E element)
: Returns the greatest element in the set strictly less than the given element, or null if there is no such element.These methods can be used to find elements in the TreeSet
based on certain criteria, such as finding the next or previous element in the set relative to a given element.
Overall, TreeSet
is a powerful class for working with sorted sets of data in Java, with efficient methods for finding, adding, and removing elements in the set.