In Java, LinkedHashSet
is available. util
package and it is the child class of HashSet
. with LinkedHashSet
we can maintain the order of elements which is not possible with HashSet
. This ordering in LinkedHashSet
is achieved by using a doubly linked list.

LinkedHashSet
is exactly same as HashSet (including constructors and methods) except for the following references. For a detailed explanation of the Constructors and methods of HashSet
check this tutorial – HashSet in Java: Complete Tutorial
HashSet | LinkedHashSet |
---|---|
1. The underline Data structure for HashSet is HashTable | 1. The underline Data structure for LinkedHashSet is a combination of HashTable and LinkedList. |
2. In HashSet insertion order is not preserved | 2. In LinkedHashSet insertion order is preserved. |
3. Introduced in Java 1.2v | 3. Introduced in Java 1.4v |
LinkedHashSet Java Example
import java.util.LinkedHashSet;
public class LinkedHashSetDemo {
public static void main(String[] args) {
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("The"); //Insertion
linkedHashSet.add("Code"); //Insertion
linkedHashSet.add("Data"); //Insertion
linkedHashSet.add("Java"); //Insertion
linkedHashSet.remove("Java"); //Deletion or removing element
//Retrival of elements
for(String element : linkedHashSet){
System.out.println(element);
}
}
}

11 thoughts on “LinkedHashSet in Java : Complete Guide”