Back to Java
2026-01-145 min read

Java LinkedHashSet

Learn Java LinkedHashSet step by step with clear examples and exercises.

Title: Java LinkedHashSet - A Deep Dive into a Frequently Used Collection Class

Why This Matters

In Java, handling collections is an essential part of programming. The LinkedHashSet is one such collection class that offers the advantages of both HashSet and LinkedList. It maintains insertion order while providing fast access to elements like a HashSet. Understanding how to use LinkedHashSet can help you solve real-world problems more efficiently, improve your coding skills, and prepare for job interviews or exams.

Prerequisites

To follow this lesson, you should be familiar with the following concepts:

  • Java basics (variables, methods, classes)
  • Interfaces (Collection, Set)
  • HashSet class
  • Basic data structures (arrays, linked lists)

Core Concept

What is LinkedHashSet?

LinkedHashSet is a subclass of HashSet that maintains the insertion order of its elements. It implements the Map interface, which means it stores unique elements in a key-value pair format, where each element is the key, and its value is always null. The LinkedHashSet class uses a linked list to store its elements, with each node containing an entry (key-value pair) and a reference to the next node.

Key features of LinkedHashSet:

  1. Ordered collection: LinkedHashSet maintains the order in which elements are inserted. This makes it useful when you need to preserve the insertion order, such as when dealing with logs or sequences.
  2. Fast access: Like HashSet, LinkedHashSet provides fast access to its elements using a hash table. This means that searching for an element, adding an element, and removing an element all have O(1) average-case complexity.
  3. Memory efficiency: LinkedHashSet is more memory-efficient than ArrayList or Vector because it doesn't store duplicate elements and doesn't waste space on empty elements.
  4. Customizable order: You can control the order of elements in a LinkedHashSet by specifying a AccessOrder when creating the set. The default value is ACCESS_ORDER_NONE, which means no specific order is maintained. To maintain access order, use ACCESS_ORDER_LRU (Least Recently Used) or ACCESS_ORDER_LFU (Least Frequently Used).

Creating a LinkedHashSet

To create a LinkedHashSet, you can use the following constructor:

public LinkedHashSet<E> (int initialCapacity, float loadFactor, int accessOrder)
  • initialCapacity: The initial number of buckets in the hash table.
  • loadFactor: The load factor for the hash table. It determines when to resize the hash table. The default value is 0.75.
  • accessOrder: The order to be maintained by the LinkedHashSet. Use one of the following values: ACCESS_ORDER_NONE, ACCESS_ORDER_LRU, or ACCESS_ORDER_LFU.

Here's an example of creating a LinkedHashSet with default parameters:

import java.util.*;

public class Main {
public static void main(String[] args) {
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("Apple");
linkedHashSet.add("Banana");
linkedHashSet.add("Orange");

System.out.println(linkedHashSet); // [Apple, Banana, Orange]
}
}

Accessing and modifying elements in LinkedHashSet

You can access elements in a LinkedHashSet using the Iterator, for-each loop, or the get() method. To remove an element, use the remove() method. Here's an example:

import java.util.*;

public class Main {
public static void main(String[] args) {
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("Apple");
linkedHashSet.add("Banana");
linkedHashSet.add("Orange");

for (String fruit : linkedHashSet) {
System.out.println(fruit);
}

linkedHashSet.remove("Banana");
System.out.println(linkedHashSet); // [Apple, Orange]
}
}

When to use LinkedHashSet?

Use LinkedHashSet when you need a collection that:

  1. Stores unique elements in insertion order.
  2. Provides fast access to its elements like a HashSet.
  3. Is more memory-efficient than ArrayList or Vector.
  4. Can maintain the order of elements based on access patterns (LRU or LFU).

Worked Example

Let's create a LinkedHashSet that maintains the order of access and stores unique URLs visited by a web browser. We will use ACCESS_ORDER_LRU to maintain the least recently used URLs.

import java.util.*;

public class Main {
public static void main(String[] args) {
LinkedHashSet<String> urls = new LinkedHashSet<>(10, 0.75f, AccessOrder.ACCESS_ORDER_LRU);

// Visit some URLs
urls.add("https://www.google.com");
urls.add("https://www.wikipedia.org");
urls.add("https://www.yahoo.com");
urls.add("https://www.bing.com");
urls.add("https://www.amazon.com");

// Print the URLs in the order they were accessed (LRU)
for (String url : urls) {
System.out.println(url);
}

// Visit some more URLs and print them again to see the updated order (LRU)
urls.add("https://www.facebook.com");
urls.add("https://www.twitter.com");
System.out.println();
for (String url : urls) {
System.out.println(url);
}
}
}

Output:

https://www.google.com
https://www.wikipedia.org
https://www.yahoo.com
https://www.bing.com
https://www.amazon.com

<URL after visiting Facebook and Twitter>
https://www.twitter.com
https://www.facebook.com
https://www.google.com
https://www.wikipedia.org
https://www.yahoo.com
https://www.bing.com
https://www.amazon.com

Common Mistakes

  1. Forgetting to import the LinkedHashSet class: Make sure you have imported java.util.LinkedHashSet at the beginning of your code.
  2. Using LinkedList instead of LinkedHashSet: LinkedList maintains the order of insertion, but it does not guarantee unique elements like LinkedHashSet.
  3. Not specifying the access order: If you don't specify an access order when creating a LinkedHashSet, it will maintain no specific order (ACCESS_ORDER_NONE).
  4. Assuming that LinkedHashSet is thread-safe: Unlike HashSet and TreeSet, LinkedHashSet is not thread-safe. Use Collections.synchronizedLinkedHashSet() to make it thread-safe if needed.
  5. Not understanding the difference between LinkedHashSet and other collections: Understand when to use LinkedHashSet, ArrayList, HashSet, TreeSet, or other Java collections based on your requirements.

Practice Questions

  1. Create a LinkedHashSet that maintains the order of insertion and stores unique characters in a string. Print the characters in the order they were inserted.
  2. Implement a simple web browser that uses a LinkedHashSet to store the history of visited URLs (LRU). Allow the user to visit new URLs, print the current history, and clear the history.
  3. Create a program that simulates a cache using a LinkedHashSet. The cache should store key-value pairs, where keys are strings and values are integers. When the cache reaches its maximum size, the least recently used items should be evicted to make room for new ones.

FAQ

  1. What is the difference between LinkedHashSet and HashSet?
  • LinkedHashSet maintains the order of insertion, while HashSet does not.
  1. Can I use LinkedHashSet as a thread-safe collection?
  • No, LinkedHashSet is not thread-safe by default. Use Collections.synchronizedLinkedHashSet() to make it thread-safe if needed.
  1. Is LinkedHashSet more memory-efficient than ArrayList or Vector?
  • Yes, LinkedHashSet is more memory-efficient because it doesn't store duplicate elements and doesn't waste space on empty elements.
  1. Can I specify the order of elements in a LinkedHashSet based on access patterns?
  • Yes, use ACCESS_ORDER_LRU (Least Recently Used) or ACCESS_ORDER_LFU (Least Frequently Used) when creating the set to maintain the desired order.
Java LinkedHashSet | Java | XQA Learn