LinkedHashSet in Java

In this tutorial, we will learn about LinkedHashSet in Java and how to use it.

As the name suggests “LinkedHashSet”, all elements are linked to each other by a doubly-linked list and also maintains order. Also, you can say it is an ordered version of HashSet.

LinkedHashSet extends HashSet Class and implements the Set interface.

Some points to remember about LinkedHashSet in Java:

  • LinkedHashSet doesn’t allows duplicates. It contains unique elements only.
  • LinkedHashSet allows NULL element and is non synchronized.
  • LinkedHashSet maintains insertion order.

The only difference between HashSet and LinkedHashSet is that: LinkedHashSet maintains the insertion order and that’s because of underlying Doubly-Linked-List.

Creating LinkedHashSet in Java:

Let’s see how to create LinkedHashSet in Java:

LinkedHashSet<T> obj = new LinkedHashSet<>();

Here, “T” indicates the type of a LinkedHashSet. For example,

// create Integer type LinkedHashSet 
LinkedHashSet<Integer> obj = new LinkedHashSet<>(); 

// create String type LinkedHashSet 
LinkedHashSet<String> obj = new LinkedHashSet<>();

LinkedHashSet Declaration:

Below is the java.util.LinkedHashSet class declaration present in the JDK:

public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable {
}

Java LinkedHashSet Example:

Let’s see a simple example of LinkedHashSet.

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    
    public static void main(String[] args) {
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet();

        // Adding element to LinkedHashSet
        linkedHashSet.add("Apple");
        linkedHashSet.add("Banana");
        linkedHashSet.add("Mango");
        linkedHashSet.add("Grapes");

        System.out.println("Printing Fruits: " + linkedHashSet);
        System.out.println("Total Fruits = " + linkedHashSet.size());

        System.out.println("Checking if Apple is present = " + linkedHashSet.contains("Apple"));
    }
}

Output:

Printing Fruits: [Apple, Banana, Mango, Grapes]
Total Fruits = 4
Checking if Apple is present = true

LinkedHashSet Vs. HashSet

Both LinkedHashSet and HashSet implements the Set interface.

  • LinkedHashSet maintains a doubly linked list internally. Due to this, it maintains the insertion order.
  • LinkedHashSet requires more storage because it maintains reference to previous and next element in the form of doubly linked list.
  • LinkedHashSet is slower than HashSet because of the underlying doubly linkedlist.

Official Doc: Read Here.

HashSet In Java