Java LinkedHashSet

In the last lesson you learned about Java HashSet. A HashSet keeps items unique but gives you no order at all. Sometimes you need both at once: each item only once, and in the same order you put them in. That is exactly what a LinkedHashSet gives you.

🤔 The problem: unique items, but order matters

Picture a “recently viewed products” row. The same product shows up many times, and you want each one only once, in the order the user saw them. The two tools you know each fail half the job:

  • A List keeps order but allows duplicates.
  • A HashSet removes duplicates but scrambles the order.
  • The product viewed first might print last, so the row looks broken.

You want one tool that does both. That tool is the LinkedHashSet.

🧩 What is a LinkedHashSet?

A LinkedHashSet is a Set with one extra promise. Here is what it gives you:

  • Stores only unique items, so duplicates are ignored.
  • Remembers the order you added them, called insertion order.
  • Prints and loops in that same order, every time.
  • Uses the same methods as HashSet: add, remove, contains, size.
  • Keeps lookups fast, just like HashSet.

Think of a guest sign-in sheet at a small event. Each guest signs once. If someone tries to sign twice, you wave them off. But the sheet also keeps the order people arrived in, from top to bottom. That is a LinkedHashSet: unique entries, kept in arrival order.

How it works under the hood

A LinkedHashSet is a hash table plus a linked list. Here is how that plays out:

  • The hash table gives fast add, remove, and contains, all O(1) on average.
  • The linked list connects each item to the next in the order added, so iteration follows insertion order.
  • Each item carries two extra links, so it uses slightly more memory than a HashSet.
  • Adding is a touch slower, because the links must be updated too.

For most programs that small cost buys predictable order. It is a bargain.

💡 Insertion order, kept

Let’s see the headline feature. The code below adds names, including a duplicate, then prints the set.

import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<String> names = new LinkedHashSet<>();
names.add("Alex");
names.add("Riya");
names.add("Arjun");
names.add("Alex"); // ❌ duplicate, ignored
System.out.println(names);
System.out.println("Size: " + names.size());
}
}

Two things to notice in the result:

  • The second “Alex” is ignored, so the size is 3, not 4.
  • The order is exactly how we added them: Alex, Riya, Arjun.
  • A HashSet might print [Riya, Arjun, Alex] or any order. The LinkedHashSet never shuffles.

Output

[Alex, Riya, Arjun]
Size: 3

🔁 Same methods you already know

Because a LinkedHashSet is a Set, it uses the exact same methods as a HashSet. There is nothing new to memorize. The example below adds numbers, removes one, checks membership, then loops.

import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> ids = new LinkedHashSet<>();
ids.add(101);
ids.add(102);
ids.add(103);
ids.remove(102); // ✅ remove by value
System.out.println(ids.contains(101)); // ✅ true
System.out.println("Size: " + ids.size());
for (int id : ids) {
System.out.println(id);
}
}
}

What the result shows:

  • We add three ids, remove 102, and 101 is still there.
  • The loop prints 101 then 103, in insertion order, with 102 gone.
  • Removing an item does not disturb the order of the rest.

Output

true
Size: 2
101
103

Here are the everyday methods, identical to HashSet:

  • add(item) puts an item in and returns false if it was already present.
  • remove(item) deletes that value and returns true if it was actually there.
  • contains(item) tells you true or false for membership, very fast.
  • size() gives the number of items in the set.
  • isEmpty() returns true when the set has no items.
  • clear() empties the set in one call.

It allows one null value. And add returning false tells you the item was already there, handy for “have we seen this before?” checks.

🎯 The star use: dedupe a list and keep order

Got a list with duplicates and want each value once, in the original order? Pass the list straight into the LinkedHashSet constructor. One line does it.

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> viewed = Arrays.asList(
"Shoes", "Bag", "Shoes", "Watch", "Bag", "Hat"
);
LinkedHashSet<String> unique = new LinkedHashSet<>(viewed);
System.out.println(unique);
System.out.println("Distinct items: " + unique.size());
}
}

What the constructor does for you:

  • Adds every item from the list in turn.
  • Drops duplicates on the way in, so the repeats of “Shoes” and “Bag” are ignored.
  • Keeps each value where it first appeared, so “Shoes” stays first.
  • A HashSet would give 4 items too, but scrambled. This keeps the user’s order.

Output

[Shoes, Bag, Watch, Hat]
Distinct items: 4

🆚 HashSet vs LinkedHashSet vs TreeSet

Java gives you three main sets. They all keep items unique. They differ in order, speed, and memory.

Feature HashSet LinkedHashSet TreeSet
Order None (looks random) Insertion order Sorted order
Backed by Hash table Hash table + linked list Red-black tree
add / remove / contains O(1) average O(1) average O(log n)
Memory use Lowest A bit more (for the links) More (tree nodes)
Allows null Yes, once Yes, once No (throws on null)
Pick it when You only need uniqueness, fastest You need uniqueness + insertion order You need uniqueness + sorted order

A simple way to choose: start with a HashSet. If you find you need a predictable order, switch to a LinkedHashSet. If you need the items sorted, switch to a TreeSet.

⚖️ Seeing the order difference for real

Let’s see it. The code below puts the same numbers into a HashSet and a LinkedHashSet, then prints both.

import java.util.HashSet;
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
int[] values = {50, 10, 40, 20, 30};
HashSet<Integer> hashSet = new HashSet<>();
LinkedHashSet<Integer> linkedSet = new LinkedHashSet<>();
for (int v : values) {
hashSet.add(v);
linkedSet.add(v);
}
System.out.println("HashSet: " + hashSet);
System.out.println("LinkedHashSet: " + linkedSet);
}
}

Both sets got the same numbers in the same order. What the result shows:

  • The LinkedHashSet prints them in insertion order: 50, 10, 40, 20, 30.
  • The HashSet prints an internal order with no link to how we added them.
  • For small integers a HashSet can look sorted by luck, but that is not a promise.

Output

HashSet: [50, 20, 40, 10, 30]
LinkedHashSet: [50, 10, 40, 20, 30]

Your HashSet output may differ

The exact HashSet order can vary by Java version and by what you store. That is the point: it is not promised. The LinkedHashSet line, though, will always be insertion order.

⚠️ Common Mistakes

A few LinkedHashSet traps to avoid.

Expecting sorted order. It keeps insertion order, not sorted order. Add big numbers first and they stay first.

// ❌ Wrong: expecting a LinkedHashSet to sort the numbers
LinkedHashSet<Integer> nums = new LinkedHashSet<>();
nums.add(30);
nums.add(10);
nums.add(20);
// This prints [30, 10, 20], NOT [10, 20, 30]
// ✅ Right: use TreeSet when you actually want sorted order
java.util.TreeSet<Integer> sorted = new java.util.TreeSet<>();
sorted.add(30);
sorted.add(10);
sorted.add(20);
// This prints [10, 20, 30]

Forgetting equals and hashCode on your own classes. It uses a hash table to spot duplicates, just like a HashSet. Override both, or identical-looking objects sneak in as separate items.

// ❌ Wrong: a class with no equals/hashCode used in a LinkedHashSet
class Tag { String label; }
// Two tags with the same label will NOT be seen as duplicates
// ✅ Right: override both, comparing the same field, so duplicates are caught
// (use Objects.equals(...) and Objects.hashCode(label) inside the overrides)

Reaching for an index. Like every set, it has no get(index). Order is kept, but there are no positions to index into. Loop with for-each instead.

✅ Best Practices

Habits for using LinkedHashSet well:

  • Pick it when you need both uniqueness and a predictable iteration order.
  • Use it to dedupe a list while keeping order, by passing the list into the constructor.
  • Do not pay for it if you do not need order. A plain HashSet uses less memory.
  • Remember it is insertion order, not sorted. Use a TreeSet when you want sorting.
  • Always override equals and hashCode together for any custom class you store.
  • Treat it as a drop-in for HashSet. The methods are identical, so swapping is easy.

🧩 What You’ve Learned

Nicely done. Let’s recap LinkedHashSet.

  • ✅ A LinkedHashSet stores unique items and keeps them in insertion order.
  • ✅ It is backed by a hash table plus a linked list, so lookups stay O(1) on average.
  • ✅ It uses the same methods as HashSet: add, remove, contains, size, and more.
  • ✅ It costs slightly more memory than a HashSet to hold the ordering links.
  • ✅ Its best use is to dedupe a list while preserving order in one line.
  • ✅ Order is insertion order, not sorted order; use a TreeSet for sorting.
  • ✅ For your own classes, override equals and hashCode so duplicates are caught.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What order does a LinkedHashSet keep items in?

    Why: A LinkedHashSet keeps items in the order you added them, called insertion order.

  2. 2

    What is a LinkedHashSet backed by?

    Why: It uses a hash table for fast lookups and a linked list to remember insertion order.

  3. 3

    Compared to a HashSet, a LinkedHashSet generally uses...

    Why: The extra linked list that tracks order means a LinkedHashSet uses a bit more memory than a HashSet.

  4. 4

    Which set should you use when you need unique items in SORTED order?

    Why: A LinkedHashSet keeps insertion order, not sorted order. Use a TreeSet for sorted order.

🚀 What’s Next?

A LinkedHashSet keeps insertion order. But what if you want your unique items kept in sorted order automatically, smallest to largest? Java has a set built for that: the TreeSet. Let’s learn it next.

Java TreeSet

Share & Connect