Java Academy Logo

Set Implementations in Java

Understanding HashSet, LinkedHashSet, and TreeSet

What are Set Implementations?

Set implementations in Java are collections that store unique elements with no duplicates. Each implementation differs in how it orders elements—some maintain no order, others preserve insertion order, and some automatically sort elements. Understanding these differences helps you choose the right Set for your needs.

1

HashSet

Simple explanation

  • Stores items using hashing
  • No specific order (elements appear randomly)

Example

HashSetExample.java
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");

System.out.println(set); 
// Output might be: [Banana, Cherry, Apple] (order is random)
2

LinkedHashSet

Simple explanation

  • Stores items in the order you add them
  • Maintains insertion order

Example

LinkedHashSetExample.java
Set<String> set = new LinkedHashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");

System.out.println(set);
// Output: [Apple, Banana, Cherry] (same order as inserted)
3

TreeSet

Simple explanation

  • Stores items in sorted (ascending) order
  • Uses a Red-Black Tree under the hood
  • Sorting happens automatically

Example

TreeSetExample.java
Set<String> set = new TreeSet<>();
set.add("Cherry");
set.add("Apple");
set.add("Banana");

System.out.println(set);
// Output: [Apple, Banana, Cherry] (sorted alphabetically)

Quick Summary

Set TypeOrder of ElementsHow It Works
HashSet❌ No orderHashing
LinkedHashSet✔ Keeps insertion orderLinked list + Hashing
TreeSet✔ Sorted orderRed-Black Tree

Key Differences at a Glance

HashSet

Fastest performance

Random order

Best for lookup

LinkedHashSet

Predictable order

Insertion order preserved

Good for iteration

TreeSet

Automatically sorted

Ascending order

Slower than HashSet