LinkedHashSet in java

Let’s learn LinkedHashSet in java.

LinkedHashSet in java

Underlying data structure for LinkedHashSet is HashTable and LinkedList.

LinkedHashSet implementation in java – Insertion order in LinkedHashSet is preserved and not allow duplicate elements.

LinkedHashSet is child class of HashSet and was introduced in java 1.4 version.

Also read – HashSet in java

LinkedHashSet contains only unique elements.

Syntax:

LinkedHashSet<String> lhs = new LinkedHashSet<String>();

LinkedHashSet constructors:

LinkedHashSet(): this constructor constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).

LinkedHashSet(Collection<? extends E> c): this constructor constructs a new linked hash set with the same elements as the specified collection.

Also read – treeset in java

LinkedHashSet(int initialCapacity): this constructor constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).

LinkedHashSet(int initialCapacity, float loadFactor): this constructor constructs a new, empty linked hash set with the specified initial capacity and load factor.

Now let’s see an example on LinkedHashSet.

import java.util.LinkedHashSet;
public class LinkedHashsetExample
{
   public static void main(String[] args)
   {
      LinkedHashSet<String> lhs = new LinkedHashSet<String>();
      // add elements to LinkedHashSet
      lhs.add("Anteater");
      lhs.add("Bear");
      lhs.add("Cheetah");
      lhs.add("Deer");
      // will not add new element as Anteater already exists
      lhs.add("Anteater");
      lhs.add("Elephant");
      System.out.println("LinkedHashSet size: " + lhs.size());
      System.out.println("Given LinkedHashSet: " + lhs);
      System.out.println("Deer removed from LinkedHashSet: " + lhs.remove("Deer"));
      System.out.println("Remove Zebra which is not present: " + lhs.remove("Zebra"));
      System.out.println("Check if Anteater is present: " + lhs.contains("Anteater"));
      System.out.println("New LinkedHashSet: " + lhs);
   }
}


Output:

LinkedHashSet size: 5
Given LinkedHashSet: [Anteater, Bear, Cheetah, Deer, Elephant]
Deer removed from LinkedHashSet: true
Remove Zebra which is not present: false
Check if Anteater is present: true
New LinkedHashSet: [Anteater, Bear, Cheetah, Elephant]