Java HashSet and TreeSet – Complete Guide with Examples
Learn Java HashSet and TreeSet, their differences, features, and usage in storing unique elements efficiently, with examples of adding, removing, and traversing elements.
HashSet and TreeSet in Java – Complete Detailed Tutorial
In Java, Set interface is implemented by HashSet and TreeSet. Both store unique elements, but differ in ordering and performance.
1. HashSet
- Implements Set interface
- Stores unique elements, unordered
- Allows null value
- Backed by hash table, fast operations for add, remove, and contains
- Does not maintain insertion order
Common Methods:
| MethodDescription | |
| add(E e) | Adds element |
| remove(Object o) | Removes element |
| contains(Object o) | Checks if element exists |
| size() | Returns number of elements |
| iterator() | Returns iterator to traverse |
Example – Using HashSet
Output (order may vary):
2. TreeSet
- Implements Set interface, also SortedSet
- Stores unique elements in sorted (ascending) order
- Does not allow null values
- Backed by Red-Black tree (self-balancing binary search tree)
Common Methods:
| MethodDescription | |
| add(E e) | Adds element |
| remove(Object o) | Removes element |
| contains(Object o) | Checks if element exists |
| first() | Returns first (lowest) element |
| last() | Returns last (highest) element |
| iterator() | Returns iterator in ascending order |
Example – Using TreeSet
Output:
3. HashSet vs TreeSet
| FeatureHashSetTreeSet | ||
| Order | Unordered | Sorted (ascending) |
| Null allowed | Yes | No |
| Performance | Faster (O(1) for add, remove, contains) | Slower (O(log n)) |
| Implementation | Hash table | Red-Black tree |
| Use case | When order is not important | When sorted order is required |
4. Key Points
- Both HashSet and TreeSet store unique elements only
- HashSet: best for fast lookup, no ordering guarantee
- TreeSet: best for sorted elements, implements NavigableSet
- Iterator can be used to traverse both
5. Summary
- HashSet: unordered, allows null, fast operations
- TreeSet: ordered, no null, slightly slower, sorted elements
- Choose based on requirement of order and performance