0
0
JavaComparisonBeginner · 4 min read

HashSet vs TreeSet vs LinkedHashSet in Java: Key Differences and Usage

In Java, HashSet stores elements without order and offers fast operations, TreeSet stores elements in sorted order with slower operations, and LinkedHashSet maintains insertion order with performance between the two. Choose based on whether you need sorting, order preservation, or fastest access.
⚖️

Quick Comparison

Here is a quick overview of the main differences between HashSet, TreeSet, and LinkedHashSet:

FeatureHashSetTreeSetLinkedHashSet
OrderingNo order (random)Sorted order (natural or comparator)Insertion order
Performance (add, remove, contains)O(1) averageO(log n)O(1) average
Allows null elementsYes (one null allowed)NoYes (one null allowed)
Underlying data structureHash tableRed-Black treeHash table + doubly linked list
Use caseFast access without orderSorted data neededPreserve insertion order
⚖️

Key Differences

HashSet uses a hash table to store elements, so it does not guarantee any order of elements. It provides the fastest performance for basic operations like add, remove, and contains, averaging constant time complexity.

TreeSet stores elements in a balanced red-black tree, which keeps elements sorted either by their natural order or a custom comparator. This sorting comes with a cost: operations take logarithmic time, which is slower than HashSet. Also, TreeSet does not allow null elements because it needs to compare elements.

LinkedHashSet combines a hash table with a linked list to maintain the order in which elements were inserted. It offers predictable iteration order and performance close to HashSet, but with a slight overhead to maintain the linked list. It allows one null element like HashSet.

⚖️

Code Comparison

Here is how you add elements and print them using HashSet:

java
import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("Apple");
        set.add("Banana");
        set.add("Cherry");
        set.add("Apple"); // duplicate ignored

        for (String fruit : set) {
            System.out.println(fruit);
        }
    }
}
Output
Banana Apple Cherry
↔️

TreeSet Equivalent

Here is the same example using TreeSet which prints elements in sorted order:

java
import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        TreeSet<String> set = new TreeSet<>();
        set.add("Apple");
        set.add("Banana");
        set.add("Cherry");
        set.add("Apple"); // duplicate ignored

        for (String fruit : set) {
            System.out.println(fruit);
        }
    }
}
Output
Apple Banana Cherry
🎯

When to Use Which

Choose HashSet when you want the fastest performance and do not care about element order. Use TreeSet when you need elements sorted automatically, such as for range queries or ordered iteration. Pick LinkedHashSet when you want to preserve the order elements were added while still having fast access.

In summary, HashSet is best for speed without order, TreeSet for sorted data, and LinkedHashSet for predictable iteration order.

Key Takeaways

HashSet offers fastest operations but no order guarantee.
TreeSet keeps elements sorted but with slower performance.
LinkedHashSet preserves insertion order with near HashSet speed.
Use TreeSet if you need sorted data, otherwise choose based on order needs.
HashSet and LinkedHashSet allow one null element; TreeSet does not.