How do you store elements in a set while keeping their insertion order?

To store elements in a Set while maintaining the order in which they were added, Java provides the LinkedHashSet class. LinkedHashSet combines the uniqueness property of a Set with a linked list structure that preserves insertion order during iteration.

Key Points

Why Not HashSet?

HashSet does not guarantee any iteration order.

Example

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

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

The output order may vary and should not be relied upon.

Why Use LinkedHashSet?

LinkedHashSet remembers the insertion sequence and returns elements in the same order.

Example

Java → Spring → Hibernate

The iteration order remains the same.

Example

Suppose we want to store unique technologies while preserving the order in which they were added.

import java.util.LinkedHashSet;
import java.util.Set;

public class Demo {

    public static void main(String[] args) {

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

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

        System.out.println(technologies);
    }
}

Output

[Java, Spring, Hibernate]

Notice

Comparison of Common Set Implementations

HashSet

LinkedHashSet

TreeSet

Real-World Use Cases

Interview Tip

A concise interview answer is

Use LinkedHashSet when you need a Set that prevents duplicate elements while preserving the order in which elements were inserted. It achieves this by maintaining a linked list alongside the hash table, ensuring predictable iteration order.

Last updated: 11 November 2026

Previous question: Which algorithms do Arrays.sort() and Collections.sort() use?

Next question: How do you store elements so that they stay sorted?

More Core Java - Level II interview questions

All Core Java - Level II questions