What is the usage of TreeSet in Java?

TreeSet is a class in the Java collection framework that extends the AbstractSet class and implements the NavigableSet interface. It is based on the Red-Black Tree data structure and has the following characteristics:

  1. Elements in a TreeSet are ordered by default according to their natural order, but a custom sorting rule can also be specified by passing a Comparator object.
  2. In a TreeSet, duplicate elements are not allowed, meaning that all elements in the collection are unique.
  3. TreeSet allows for efficient insertion, deletion, and lookup operations with a time complexity of O(log n), where n is the number of elements in the set.
  4. TreeSet is not thread-safe, so if you want to use it in a multi-threaded environment, you need to synchronize it using the synchronizedSortedSet method provided by the Collections class.

Common methods of TreeSet include:

  1. add(E e): Add an element to the collection.
  2. Remove a specified element from the collection.
  3. contains(Object o): Determines if the collection contains the specified element.
  4. size(): returns the number of elements in the collection.
  5. isEmpty(): check if the collection is empty.
  6. iterator(): returns an iterator that can be used to iterate over the elements in the collection.
  7. first(): return the first element in the collection.
  8. last(): returns the last element in the collection.
  9. higher(E e): returns the smallest element in the collection that is higher than the given element.
  10. Return the maximum element in the collection that is lower than the given element.

In addition to the methods mentioned above, TreeSet also inherits other methods defined in the AbstractSet and AbstractCollection classes, as well as some navigation methods defined in the NavigableSet interface, such as ceiling, floor, higher, and lower.

In conclusion, TreeSet provides an ordered and unique collection implementation that is suitable for scenarios requiring sorting and searching of elements.

bannerAds