What is the Difference Between TreeSet and TreeMap?

🆚 Go to Comparative Table 🆚

The main difference between TreeSet and TreeMap in Java is that a TreeSet is a set of unique elements, while a TreeMap is a map that associates a key with a value. Here are some key differences between the two:

  • Structure: TreeSet is an implementation of the SortedSet interface, while TreeMap is an implementation of the Map interface and NavigableMap.
  • Elements: TreeSet stores unique elements, and it does not allow duplicates. TreeMap, on the other hand, uses two objects called key and value, where keys are unique, and values can be duplicated.
  • Sorting: Both TreeSet and TreeMap store their elements in sorted order. However, in TreeSet, elements are stored in ascending order based on their natural ordering or a custom order. TreeMap also has its keys in sorted order.
  • Access: TreeSet allows you to look up elements by value, while TreeMap allows you to look up values by key. If you need to iterate over the elements in sorted order, use TreeSet. For iterating over the keys or key-value pairs in sorted order, use TreeMap.

Both TreeSet and TreeMap use a self-balancing binary search tree (specifically, a red-black tree) to store their elements in sorted order.

Comparative Table: TreeSet vs TreeMap

Here is a table summarizing the differences between TreeSet and TreeMap:

Feature TreeSet TreeMap
Implements SortedSet Map
Object type Single object Key-value pairs
Duplicates Does not allow duplicates Allows duplicate values
Insertion order Insertion order is not maintained Insertion order is preserved
Retrieval time O(log N) O(log N)
Implementing interface NavigableSet NavigableMap

The main difference between TreeSet and TreeMap is that TreeSet implements the SortedSet interface and stores single objects, while TreeMap implements the Map interface and stores key-value pairs in ascending order. TreeSet does not allow duplicate objects, whereas TreeMap allows duplicate values. The insertion order of elements is not maintained in TreeSet, but it is preserved in TreeMap. Both data structures provide O(log N) retrieval time and implement the NavigableSet and NavigableMap interfaces, respectively.