Java LinkedHashSet is used to store unique elements while maintaining the insertion order in Java.
In this chapter, you will learn about the Java LinkedHashSet class, its features, and why it is used in collections along with the examples.
Java LinkedHashSet class is a Hashtable and Linked List implementation of the Set interface. It inherits the HashSet class and implements the Set interface.
The important points about the Java LinkedHashSet class are:
Note: Keeping the insertion order in LinkedHashSet has some additional costs, both in terms of extra memory and extra CPU cycles.
Therefore, if maintaining insertion order is not required, it is better to use HashSet or HashMap instead.
The LinkedHashSet class extends the HashSet class, which implements the Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.
The below image shows the hierarchy of the LinkedHashSet class:

Let's see the declaration for java.util.LinkedHashSet class.
Java LinkedHashSet class provides different constructors to create and initialize a LinkedHashSet.
It is used to construct a default LinkedHashSet.
Here is the syntax:
It is used to construct a LinkedHashSet containing the elements of the specified collection.
Here is the syntax:
It is used to construct a LinkedHashSet with the specified initial capacity and default load factor.
Here is the syntax:
It is used to construct a LinkedHashSet with the specified capacity and load factor.
Here is the syntax:
LinkedHashSet is used to store elements in insertion order, and we can traverse the elements using Iterator.
In this example, we are creating a LinkedHashSet, adding elements, and traversing them using an Iterator.
Output:
One Two Three Four Five
LinkedHashSet does not allow duplicate elements. If duplicate values are added, they are ignored automatically.
In this example, we are adding duplicate elements to LinkedHashSet, but it stores only unique values.
Output:
Ravi Vijay Ajay
The LinkedHashSet elements can be removed by using the remove() method.
In this example, we are removing elements from LinkedHashSet using the remove() method.
Output:
The hash set is: [Java, T, Point, Good, Website] true After removing the element, the hash set is: [Java, T, Point, Website] false
LinkedHashSet can also store user-defined objects.
In this example, we are storing user-defined Book objects in a LinkedHashSet and traversing them.
Output:
101 Let us C Yashwant Kanetkar BPB 8 102 Data Communications & Networking Forouzan Mc Graw Hill 4 103 Operating System Galvin Wiley 6
We request you to subscribe our newsletter for upcoming updates.