LinkedHashSet in Java : Complete Guide

In Java, LinkedHashSet is available in java.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 in Java

LinkedHashSet is the 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

1. The underlying Data structure for LinkedHashSet is a combination of HashTable and LinkedList.1. The underlying Data structure for LinkedHashSet combines HashTable and LinkedList.
2. In HashSet insertion order is not preserved1. The underlying Data structure for HashSet is HashTable
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){
LinkedHashSet Java Example

Similar Java Tutorials