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

  1. Implements Set interface
  2. Stores unique elements, unordered
  3. Allows null value
  4. Backed by hash table, fast operations for add, remove, and contains
  5. 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


import java.util.HashSet;
import java.util.Set;

public class Main {
public static void main(String[] args) {
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // duplicate ignored

System.out.println("HashSet: " + fruits);
fruits.remove("Banana");
System.out.println("After removal: " + fruits);
System.out.println("Contains Apple? " + fruits.contains("Apple"));
}
}

Output (order may vary):


HashSet: [Apple, Orange, Banana]
After removal: [Apple, Orange]
Contains Apple? true

2. TreeSet

  1. Implements Set interface, also SortedSet
  2. Stores unique elements in sorted (ascending) order
  3. Does not allow null values
  4. 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


import java.util.Set;
import java.util.TreeSet;

public class Main {
public static void main(String[] args) {
Set<String> fruits = new TreeSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // duplicate ignored

System.out.println("TreeSet: " + fruits);
System.out.println("First element: " + ((TreeSet<String>) fruits).first());
System.out.println("Last element: " + ((TreeSet<String>) fruits).last());
fruits.remove("Banana");
System.out.println("After removal: " + fruits);
}
}

Output:


TreeSet: [Apple, Banana, Orange]
First element: Apple
Last element: Orange
After removal: [Apple, Orange]

3. HashSet vs TreeSet

FeatureHashSetTreeSet
OrderUnorderedSorted (ascending)
Null allowedYesNo
PerformanceFaster (O(1) for add, remove, contains)Slower (O(log n))
ImplementationHash tableRed-Black tree
Use caseWhen order is not importantWhen sorted order is required

4. Key Points

  1. Both HashSet and TreeSet store unique elements only
  2. HashSet: best for fast lookup, no ordering guarantee
  3. TreeSet: best for sorted elements, implements NavigableSet
  4. Iterator can be used to traverse both

5. Summary

  1. HashSet: unordered, allows null, fast operations
  2. TreeSet: ordered, no null, slightly slower, sorted elements
  3. Choose based on requirement of order and performance