LinkedHashSet class in Java
Set is a collection that cannot contain duplicate elements.
LinkedHashSet class is a hash table and linked list implementation of the Set interface. That is, it stores its elements in a hash table with a linked list. Here, the insertion order is preserved.
LinkedHashSet differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion order).
LinkedHashSet class permits the null
element. It must be noted that a set may contain at most one null element (not more than one because no duplicates are allowed in a set).
Java provides the LinkedHashSet class as part of the Java Collections Framework. For an overview of the Java Collections Framework, check out my post Overview of the Java Collections Framework.
The following example illustrates the LinkedHashSet class.
Example
Output
As you can see from the above output, there are no duplicate elements in the LinkedHashSet. Also, LinkedHashSet preserved the insertion order of the elements.
The above program showed the use of some of the common methods of the LinkedHashSet class. For a complete list of all the available methods, refer the official docs.
Now since you know how to use the LinkedHashSet class, check out other implementations of the Set interface: