← Back to Home

LinkedHashSet

LinkedHashSet is an implementation of the Set interface that combines the uniqueness guarantee of HashSet with the predictable iteration order of a linked list. It is used when you need unique elements while preserving insertion order. This is a common interview topic, often compared with HashSet and TreeSet.

What Is LinkedHashSet?

  • Implementation of Set
  • Stores unique elements only
  • Maintains insertion order
  • Allows one null value
  • Part of java.util package
Set<String> set = new LinkedHashSet<>();
          

Position in Collection Hierarchy

Iterable
   └── Collection
        └── Set
             └── LinkedHashSet
          

How LinkedHashSet Works Internally (Interview Favorite)

  • Backed by a LinkedHashMap
  • Uses hash table + doubly linked list
  • Hash table → fast lookup
  • Linked list → preserves insertion order
HashMap + LinkedList = LinkedHashSet
          

Key Characteristics of LinkedHashSet

  • Maintains insertion order
  • No duplicate elements
  • Faster than TreeSet
  • Slightly slower than HashSet
  • Not synchronized (not thread-safe)

Creating a LinkedHashSet

LinkedHashSet<Integer> set = new LinkedHashSet<>();
          

Commonly Used Methods

set.add(10);
set.add(20);
set.add(10); // duplicate ignored

set.remove(20);
set.contains(10);
set.size();
          

Order Preservation Example

LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("Java");
set.add("Python");
set.add("C++");

System.out.println(set);
          

Output:

[Java, Python, C++]
          
  • ✔ Order preserved
  • ✔ Duplicates ignored

Performance Complexity

Operation Time Complexity
add O(1)
remove O(1)
contains O(1)
iteration O(n)

Null Handling

  • Allows one null element
set.add(null);
          
  • ✔ Allowed
  • ❌ Second null ignored

LinkedHashSet vs HashSet vs TreeSet

Feature HashSet LinkedHashSet TreeSet
Order ❌ No ✔ Insertion ✔ Sorted
Performance Fastest Slightly slower Slowest
Null allowed ✔ One ✔ One ❌ No
Internal DS HashMap LinkedHashMap Tree

When to Use LinkedHashSet

  • Uniqueness is required
  • Insertion order must be preserved
  • Fast lookup needed
  • Predictable iteration order

When NOT to Use LinkedHashSet

  • Sorting is required
  • Memory usage must be minimal
  • Order does not matter (use HashSet)

Common Beginner Mistakes

  • Assuming sorted order
  • Using LinkedHashSet unnecessarily when HashSet is sufficient
  • Ignoring memory overhead
  • Forgetting equals() and hashCode() importance

Interview-Ready Answers

Short Answer

LinkedHashSet is a Set implementation that maintains insertion order.

Detailed Answer

In Java, LinkedHashSet extends HashSet and uses a LinkedHashMap internally to store unique elements while preserving insertion order. It provides constant-time performance and predictable iteration order.

LinkedHashSet Examples

1. Creating a LinkedHashSet

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<String> set = new LinkedHashSet<>();
        set.add("Java");
        set.add("API");
        System.out.println(set);
    }
}
          

Output:

[Java, API]
          

2. Maintains Insertion Order

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<String> set = new LinkedHashSet<>();
        set.add("B");
        set.add("A");
        set.add("C");
        System.out.println(set);
    }
}
          

Output:

[B, A, C]
          

3. Does Not Allow Duplicates

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<Integer> set = new LinkedHashSet<>();
        set.add(10);
        set.add(10);
        set.add(20);
        System.out.println(set);
    }
}
          

Output:

[10, 20]
          

4. Allows One null

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<String> set = new LinkedHashSet<>();
        set.add(null);
        set.add(null);
        set.add("Java");
        System.out.println(set);
    }
}
          

Output:

[null, Java]
          

5. Iterating Using for-each Loop

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<String> set =
                new LinkedHashSet<>(Arrays.asList("X", "Y", "Z"));
        for (String s : set) {
            System.out.println(s);
        }
    }
}
          

6. Iterating Using Iterator

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<Integer> set =
                new LinkedHashSet<>(Arrays.asList(1, 2, 3));
        Iterator<Integer> it = set.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
          

7. Removing Elements

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<String> set =
                new LinkedHashSet<>(Arrays.asList("A", "B", "C"));
        set.remove("B");
        System.out.println(set);
    }
}
          

Output:

[A, C]
          

8. Removing While Iterating (Safe Way)

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<Integer> set =
                new LinkedHashSet<>(Arrays.asList(1, 2, 3));
        Iterator<Integer> it = set.iterator();
        while (it.hasNext()) {
            if (it.next() == 2) {
                it.remove();
            }
        }
        System.out.println(set);
    }
}
          

Output:

[1, 3]
          

9. Checking Element Existence

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<String> set =
                new LinkedHashSet<>(Arrays.asList("Java", "API"));
        System.out.println(set.contains("Java"));
    }
}
          

Output:

true
          

10. Converting List to LinkedHashSet (Remove Duplicates + Order)

import java.util.*;

class Demo {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(3, 1, 1, 2);
        LinkedHashSet<Integer> set = new LinkedHashSet<>(list);
        System.out.println(set);
    }
}
          

Output:

[3, 1, 2]
          

11. Converting LinkedHashSet to List

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<String> set =
                new LinkedHashSet<>(Arrays.asList("A", "B"));
        List<String> list = new ArrayList<>(set);
        System.out.println(list);
    }
}
          

12. size() and isEmpty()

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<String> set = new LinkedHashSet<>();
        System.out.println(set.isEmpty());
        set.add("Java");
        System.out.println(set.size());
    }
}
          

Output:

true
1
          

13. LinkedHashSet vs HashSet (Order Comparison)

import java.util.*;

class Demo {
    public static void main(String[] args) {
        Set<String> h = new HashSet<>();
        h.add("B");
        h.add("A");

        Set<String> l = new LinkedHashSet<>();
        l.add("B");
        l.add("A");

        System.out.println(h);
        System.out.println(l);
    }
}
          

Output:

[A, B]
[B, A]
          

14. Using Custom Objects (Without equals & hashCode)

class User {
    int id;
    User(int id) { this.id = id; }
}

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<User> set = new LinkedHashSet<>();
        set.add(new User(1));
        set.add(new User(1));
        System.out.println(set.size());
    }
}
          

Output:

2
          

15. Custom Objects with equals() & hashCode()

class User {
    int id;
    User(int id) { this.id = id; }

    public boolean equals(Object o) {
        return this.id == ((User)o).id;
    }

    public int hashCode() {
        return id;
    }
}

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<User> set = new LinkedHashSet<>();
        set.add(new User(1));
        set.add(new User(1));
        System.out.println(set.size());
    }
}
          

Output:

1
          

16. LinkedHashSet Internal Behavior (Concept)

LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("Java");
          

Explanation

  • Backed by LinkedHashMap
  • Maintains insertion order
  • Slightly slower than HashSet

17. Thread-Safe LinkedHashSet

import java.util.*;

class Demo {
    public static void main(String[] args) {
        Set<String> set =
            Collections.synchronizedSet(new LinkedHashSet<>());
        set.add("Safe");
        System.out.println(set);
    }
}
          

18. addAll() – Union While Preserving Order

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<Integer> s1 =
                new LinkedHashSet<>(Arrays.asList(1, 2));
        LinkedHashSet<Integer> s2 =
                new LinkedHashSet<>(Arrays.asList(2, 3));
        s1.addAll(s2);
        System.out.println(s1);
    }
}
          

Output:

[1, 2, 3]
          

19. retainAll() – Intersection While Preserving Order

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<Integer> s1 =
                new LinkedHashSet<>(Arrays.asList(1, 2, 3));
        LinkedHashSet<Integer> s2 =
                new LinkedHashSet<>(Arrays.asList(2, 3, 4));
        s1.retainAll(s2);
        System.out.println(s1);
    }
}
          

Output:

[2, 3]
          

20. Interview Summary – LinkedHashSet

import java.util.*;

class Demo {
    public static void main(String[] args) {
        LinkedHashSet<String> set = new LinkedHashSet<>();
        set.add("Ordered");
        set.add("Unique");
        set.add("Unique");
        System.out.println(set);
    }
}
          

Key Points

  • No duplicates
  • Maintains insertion order
  • Allows one null
  • Backed by LinkedHashMap
  • Slightly slower than HashSet

Key Takeaway

LinkedHashSet = HashSet + Order Preservation. Use it when you need unique elements with predictable iteration order.