Java LinkedHashSet

Introduction

The Java LinkedHashSet class is a popular implementation of the Set interface in the Java Collection Framework. It combines the advantages of HashSet and LinkedList by providing fast performance while also maintaining the insertion order of elements.

LinkedHashSet stores only unique elements, meaning duplicate values are not allowed.

The LinkedHashSet class belongs to the java.util package and internally uses a LinkedHashMap to store its elements. It maintains a doubly linked list across all entries, allowing elements to be traversed in insertion order.

What is Java LinkedHashSet?

A LinkedHashSet is a collection that stores unique elements while preserving the order in which they were inserted.

For example:

Elements inserted:


Java 
Python 
Spring 
Java 
React 
Python

Output:

Java
Python
Spring
React

Notice that:

  • Duplicate elements are ignored.
  • The insertion order is preserved.

Key Characteristics

  • Stores unique elements
  • Maintains insertion order
  • Allows one null element
  • Dynamic size
  • Uses hashing for fast lookup
  • Supports Generics
  • Not synchronized
  • Backed internally by LinkedHashMap

Java LinkedHashSet Hierarchy


Object
   │
AbstractCollection
   │
AbstractSet
   │
HashSet
   │
LinkedHashSet

The LinkedHashSet class implements:

The LinkedHashSet class implements:

  • Set
  • Collection
  • Iterable
  • Serializable
  • Cloneable

Features of Java LinkedHashSet

Some important features include:

  • Stores only unique elements
  • Preserves insertion order
  • Fast insertion, deletion, and searching
  • Allows one null value
  • Supports Generics
  • Dynamic resizing
  • Easy traversal
  • Backed by LinkedHashMap

Syntax

Import Statement


import java.util.LinkedHashSet;

or


import java.util.*;

Creating a LinkedHashSet


LinkedHashSet<String> languages = new LinkedHashSet<>();

Using the Set interface:


Set<String> languages = new LinkedHashSet<>();

Programming to the Set interface is considered a best practice because it improves code flexibility.

Constructors of LinkedHashSet

1. Default Constructor


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

Creates an empty LinkedHashSet with default capacity and load factor.

2. Constructor with Initial Capacity


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

Creates a LinkedHashSet with an initial capacity of 20.

3. Constructor with Capacity and Load Factor


LinkedHashSet<Integer> set = new LinkedHashSet<>(20,0,75f);

Creates a LinkedHashSet with:

  • Initial Capacity = 20
  • Load Factor = 0.75

4. Constructor from Another Collection


List<String> list =
        Arrays.asList("Java", "Python", "Java", "Spring");
LinkedHashSet<String> set =
        new LinkedHashSet<>(list);
System.out.println(set);

Output

[Java, Python, Spring]

Common Methods of LinkedHashSet

Method Description
addFirst() Adds an element
remove() Removes an element
contains() Checks whether an element exists
size() Returns the number of elements
isEmpty() Checks whether the Set is empty
clear() Removes all elements
iterator() Returns an iterator for traversal
addAll() Adds all elements from another collection
removeAll() Removes matching elements
retainAll() Keeps only common elements

Example 1: Creating a LinkedHashSet


import java.util.*;

public class LinkedHashSetExample {

    public static void main(String[] args) {

        LinkedHashSet<String> set =
        new LinkedHashSet<>(list);

        courses.add("Java");
        courses.add("Python");
        courses.add("Spring Boot");

        System.out.println(courses);
    }
}

Output

[Java, Python, Spring Boot]

The insertion order is maintained.

Example 2: Duplicate Elements


import java.util.*;

public class DuplicateExample {

    public static void main(String[] args) {

        LinkedHashSet<String> cities =
        new LinkedHashSet<>(list)

        numbers.add(10);
        numbers.add(20);
        numbers.add(10);
        numbers.add(30);

        System.out.println(numbers);
    }
}

Output

[10, 20, 30]

The duplicate value 10 is ignored.

Example 3: Checking an Element


import java.util.*;

public class ContainsExample {

    public static void main(String[] args) {

        LinkedHashSet cities =
                new LinkedHashSet();

        cities.add("Delhi");
        cities.add("Mumbai");

        System.out.println(cities.contains("Mumbai"));
    }
}

Output

true

Example 4: Removing an Element


import java.util.*;

public class RemoveExample {

    public static void main(String[] args) {

        LinkedHashSet fruits =
                new LinkedHashSet();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        fruits.remove("Banana");

        System.out.println(fruits);
    }
}

Output

[Apple, Mango]

Example 5: Iterating Through LinkedHashSet


import java.util.*;

public class LoopExample {

    public static void main(String[] args) {

        LinkedHashSet skills =
                new LinkedHashSet();

        skills.add("Java");
        skills.add("Spring");
        skills.add("Hibernate");

        for(String skill : skills){
            System.out.println(skill);
        }
    }
}

Output

Java
Spring
Hibernate

Elements are printed in the same order they were inserted.

How LinkedHashSet Works Internally

Internally, LinkedHashSet is backed by a LinkedHashMap.

The process works as follows:

  1. Java calculates the element’s hashCode().
  2. The element is stored in a hash table for fast lookup.
  3. A doubly linked list keeps track of insertion order.
  4. Duplicate elements are identified using equals().
  5. Only unique elements are stored.

This design combines the speed of hashing with predictable iteration order.

LinkedHashSet vs HashSet vs TreeSet

Feature HashSet LinkedHashSet TreeSet
Duplicate Elements No No No
Insertion Order No Yes No
Sorted Order No No Yes
Allows Null Yes (one) Yes (one) Yes
Internal Structure Hash Table Hash Table + Linked List Red-Black Tree
Performance Fastest Fast Slower

Time Complexity

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

Although slightly slower than HashSet due to maintaining a linked list, LinkedHashSet still offers excellent performance.

Real-life Example

Imagine you’re building an e-commerce website.

A customer recently viewed the following products:

Laptop

Keyboard

Mouse

Laptop

Monitor

Using a LinkedHashSet, the application stores:

Laptop

Keyboard

Mouse

Monitor

This ensures:

  • No duplicate products
  • Products remain in the order they were first viewed

Other real-world applications include:

  • Recently viewed products
  • Browser history
  • Playlist management
  • Navigation menus
  • Search history
  • Order processing
  • Configuration settings
  • Unique log entries

Advantages of Java LinkedHashSet

  • Maintains insertion order
  • Prevents duplicate elements
  • Fast lookup and insertion
  • Dynamic size
  • Allows one null value
  • Easy traversal
  • Supports Generics
  • Ideal when order and uniqueness are both important

Limitations of Java LinkedHashSet

  • Slightly slower than HashSet because of maintaining a linked list
  • Does not sort elements
  • No index-based access
  • Not synchronized
  • Uses more memory than HashSet

Common Mistakes

1. Expecting Sorted Order

Incorrect assumption:


10
5
20

Output remains:


10
5
20

LinkedHashSet preserves insertion order, not sorted order.

Use TreeSet if automatic sorting is required.

2. Adding Duplicate Elements


set.add("Java");
set.add("Java");

Only one “Java” is stored.

3. Forgetting Generics

Incorrect:


LinkedHashSet set = new LinkedHashSet();

Correct:


LinkedHashSet<String> languages = new LinkedHashSet<>();

4. Using get() Method

Incorrect:


set.get(0);

A LinkedHashSet does not support index-based access.

5. Ignoring equals() and hashCode() for Custom Objects

When storing custom objects, always override both equals() and hashCode() to ensure duplicate detection works correctly.

Best Practices

  • Declare variables using the Set interface.

Set&ltString&gtusers = new LinkedHashSet&lt&gt();
  • Use LinkedHashSet when insertion order is important.
  • Use HashSet if order does not matter and maximum performance is required.
  • Use TreeSet when sorted data is needed.
  • Always use Generics for type safety.
  • Override equals() and hashCode() for custom objects.

Conclusion

The Java LinkedHashSet class is an excellent choice when you need to store unique elements while preserving the insertion order. By combining the speed of hashing with the predictability of a linked list, it offers an efficient and reliable solution for many real-world applications.

Related Java Tutorials