Java ProgramsCollectionsLinkedHashSet Example

LinkedHashSet Example in Java

beginner·  Collections  ·  Set

Problem

A LinkedHashSet works like a HashSet — no duplicates, hash-based lookups — but it also threads a doubly-linked list through its entries, so iteration always follows insertion order instead of the unpredictable order a plain HashSet gives.

Add several elements to a LinkedHashSet, including a duplicate, and confirm iteration reflects the order they were first added in.

Input
add("Paris"), add("Tokyo"), add("London"), add("Paris")
Output
Paris Tokyo London

Java Program

Java
import java.util.LinkedHashSet; import java.util.Set; public class LinkedHashSetExample { public static void main(String[] args) { Set<String> cities = new LinkedHashSet<>(); cities.add("Paris"); cities.add("Tokyo"); cities.add("London"); cities.add("Paris"); // already present — insertion order stays unchanged for (String city : cities) { System.out.println(city); } } }

Output

Paris Tokyo London

Core Logic

Every distinct element remembers the order it was first inserted in, so iterating the set later reproduces that same order exactly — the duplicate add() call doesn't move Paris or add a second entry.

How It Works
  1. 1add("Paris"), add("Tokyo"), add("London") insert three cities in that order.
  2. 2add("Paris") again has no effect — Paris is already present, so the set's size and its position in the iteration order both stay unchanged.
  3. 3Internally, LinkedHashSet maintains a doubly-linked list connecting the entries in insertion order, alongside the hash table that gives fast add()/contains().
  4. 4The for-each loop walks that linked list, printing Paris, Tokyo, London — the exact order the three distinct cities were first added.
Even with a duplicate add() call in the middle, the three distinct cities print in the same order they were first inserted.
💡

Key Point: This is the key difference from plain HashSet — a HashSet gives no iteration-order guarantee at all, while LinkedHashSet guarantees insertion order, at the cost of a little extra memory for the linked list.

Complexity
Time Complexity: O(1)Space Complexity: O(n)

Why: add() and contains() still run in average-case constant time via the underlying hash table, and the extra doubly-linked list only adds a constant amount of bookkeeping per entry, not per lookup.

Key Concepts

LinkedHashSetinsertion orderadd()

Related Programs