TreeSet In Java
TreeSet in Java
TreeSet is a part of the Java Collections Framework and is an implementation of the SortedSet interface. It provides a set that is sorted in a natural order or according to a specified comparator. Unlike HashSet, TreeSet does not allow duplicate elements, and it provides efficient performance for basic operations, such as adding, removing, and searching for elements.
Declaration and Initialization
To use a TreeSet in Java, you need to import the java.util.TreeSet
package. Here's an example of declaring and initializing a TreeSet:
import java.util.TreeSet;
public class Example {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
// Adding elements to the TreeSet
numbers.add(20);
numbers.add(50);
numbers.add(5);
// No duplicate elements allowed
numbers.add(20); // This won't be added
// Accessing elements
for (Integer number : numbers) {
System.out.println(number);
}
// Removing elements
numbers.remove(5);
// Checking if an element exists
boolean exists = numbers.contains(20);
System.out.println("20 exists in the set: " + exists);
}
}
Common TreeSet Operations
Here are some commonly used operations with TreeSets:
add(element)
: Adds an element to the TreeSet.remove(element)
: Removes an element from the TreeSet.contains(element)
: Checks if the TreeSet contains a specific element.size()
: Returns the number of elements in the TreeSet.isEmpty()
: Checks if the TreeSet is empty.clear()
: Removes all elements from the TreeSet.
TreeSet is a versatile data structure when the requirement is to maintain a unique set of elements in a sorted order. It is an excellent choice for tasks that involve searching, range queries, or maintaining a sorted collection of elements.