Table of contents
1.
Introduction
2.
What is Java LinkedHashSet?
3.
Constructors for LinkedHashSet in Java
3.1.
Java
4.
Methods of LinkedHashSet in Java
4.1.
Java
5.
Performing Different Operations on the LinkedHashSet Class
5.1.
Java
5.1.1.
Output
5.1.2.
Explanation of Operations
6.
Frequently Asked Questions
6.1.
What are the disadvantages of using the LinkedHashSet?
6.2.
How do LinkedHashSets and TreeSets differ?
6.3.
Why LinkedHashMap is Faster than HashMap?
6.4.
What is the Difference Between LinkedHashSet and LinkedHashMap?
6.5.
Difference between the HashSet and LinkedHashSet.
7.
Conclusion
Last Updated: Dec 22, 2024
Easy

LinkedHashSet in Java

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Set interface in the Collection Framework is a child of Collection. It's often helpful to use LinkedHashSets to keep the order of a collection of objects when duplicates aren't allowed, and the insertion order isn't preserved. This article is about LinkedHashSet in detail.

LinkedHashSet in Java

Also Read About, Multithreading in java

What is Java LinkedHashSet?

HashSet is a child class of LinkedHashSet. It combines two data structures: Hash Table and Linked List, which is a hybrid Data Structure

In LinkedHashSet, all elements remain doubly linked across all elements in an ordered version of HashSet. In cases where you care about the iteration order, this class is better than HashSet. 

LinkedHashSet allows you to iterate through elements in the order they were inserted, while HashSet lets you iterate through elements in an unpredictable order. 

For insertion, removal, and retrieval, the LinkedHashSet exhibits the performance of order O(1). It has an initial default capacity of 16 and a load factor of 0.75.

Constructors for LinkedHashSet in Java

There are four constructors for LinkedHashSet:
 

  1. LinkedHashSet lh=new LinkedHashSet(); // A LinkedHashSet object is created with an initial capacity of 16 and a Fill ratio of 0.75 (also known as Load Factor).
     
  2. LinkedHashSet lh=new LinkedHashSet(int initialCapacity); // A LinkedHashSet with customized capacity is created.
     
  3. LinkedHashSet h=new LinkedHashSet(int initialCapacity, float load factor); //A LinkedHashSet is created with a customized initial capacity and load factor.
     
  4. LinkedHashSet h=new LinkedHashSet(Collection c); // A LinkedHashSet object is created from the given collection. This allows conversion between Collection objects.
     

Here is a java program for creating a LinkedHashSet by using another collection.

  • Java

Java

import java.util.*;
public class Main {
   public static void main(String args[]) {       
     LinkedHashSet lh=new LinkedHashSet<>(); 
     lh.add("kashish"); 
     lh.add("2022"); 
     lh.add("4");
     lh.add(null);
     lh.add("three");
     System.out.println(lh);
   }
}
You can also try this code with Online Java Compiler
Run Code


Output:

[kashish,2022,4,null,three]

Methods of LinkedHashSet in Java

Method

Description

add(e)An element is added if it isn't already in the Set.
clear()Everything in the Set is removed.
clone()This function returns a copy of the LinkedHashSet instance, which does not clone the elements.
equals()The function returns true if the specified object matches this set.
contains(Object)This set includes the element specified by the element.
isEmpty()If the Set does not contain elements, it is returned as true.
iterator()If the Set contains elements, it is returned as true.
remove(Object)This set is removed if it contains any elements.
size()It returns the size of the set.
spliterator()This function splits the elements late-binding and fail-fast.
toString()This function returns this collection as a string.
toArray()This function returns an array of all the elements in this Collection.

Below is the implementation for some methods:

  • Java

Java

import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
//creating an object for LinkedHashSet
Set < String > lh = new LinkedHashSet < String > ();

// Adding elements the  using add()
lh.add("Kashish");
lh.add("Saxena");
lh.add("21");
lh.add("Coding");
lh.add("Ninjas's");

// removing elements from the LinkedHashSet
lh.remove("21");
System.out.println("After removing the element: " + lh);

// Check if the LinkedHashSet contains an element?
System.out.println("Checking if the element is present? " + lh.contains("Coding"));

// Iterating the elements using iterators
Iterator i = lh.iterator();
while (i.hasNext())
System.out.print(i.next() + "_");
System.out.println();
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

After removing the element: ['Kashish', 'Saxena', 'Coding', 'Ninjas']
Checking if the element is present? true 
Kashish_Saxena_Coding_Ninjas's_

 

Try it by yourself on java online compiler.

Performing Different Operations on the LinkedHashSet Class

The LinkedHashSet class in Java is a part of the java.util package. It maintains the insertion order of elements while ensuring that no duplicate elements are stored. Below is an explanation of common operations that can be performed on a LinkedHashSet with an example.

  • Java

Java

import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
// Create a LinkedHashSet
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
// 1. Adding elements to the LinkedHashSet
linkedHashSet.add("Apple");
linkedHashSet.add("Banana");
linkedHashSet.add("Cherry");
linkedHashSet.add("Date");
// Duplicate elements (ignored)
linkedHashSet.add("Apple");
// 2. Displaying the LinkedHashSet
System.out.println("LinkedHashSet Elements: " + linkedHashSet);
// 3. Removing an element
linkedHashSet.remove("Banana");
System.out.println("After Removing 'Banana': " + linkedHashSet);
// 4. Checking if an element exists
boolean containsCherry = linkedHashSet.contains("Cherry");
System.out.println("Contains 'Cherry': " + containsCherry);
// 5. Checking the size
System.out.println("Size of LinkedHashSet: " + linkedHashSet.size());
// 6. Iterating through the LinkedHashSet
System.out.println("Iterating through LinkedHashSet:");
for (String element : linkedHashSet) {
System.out.println(element);
}
}
}
You can also try this code with Online Java Compiler
Run Code

Output

LinkedHashSet Elements: [Apple, Banana, Cherry, Date]
After Removing 'Banana': [Apple, Cherry, Date]
Contains 'Cherry': true
Size of LinkedHashSet: 3
Iterating through LinkedHashSet:
Apple
Cherry
Date


Explanation of Operations

  1. Adding Elements: Use the add() method to add elements. Duplicate entries are ignored.
     
  2. Removing Elements: Use the remove() method to remove a specific element.
     
  3. Checking Existence: Use the contains() method to verify if a particular element is present.
     
  4. Size: Use the size() method to get the number of elements in the set.
     
  5. Iteration: Iterate using a for-each loop to access each element in insertion order.

Frequently Asked Questions

What are the disadvantages of using the LinkedHashSet?

Element iteration is slower than with ArrayLists.
Access to random elements is inefficient.
There is an additional memory overhead involved with keeping track of the next element in the list.

How do LinkedHashSets and TreeSets differ?

The linked hash set maintains the insertion order of elements. Elements are inserted in the order they are added. Based on a Comparator supplied by TreeSet, the elements are ordered. In the absence of a comparator, elements will be sorted in their natural ascending order.

Why LinkedHashMap is Faster than HashMap?

LinkedHashMap is generally faster than HashMap for iteration because it maintains the insertion order with a linked list, which reduces overhead during iteration. HashMap, on the other hand, doesn't guarantee order, making iteration slower in some cases.

What is the Difference Between LinkedHashSet and LinkedHashMap?

LinkedHashSet is a collection that stores unique elements while maintaining insertion order, whereas LinkedHashMap stores key-value pairs with unique keys, maintaining insertion order and allowing efficient lookups, updates, and deletions based on keys.

Difference between the HashSet and LinkedHashSet.

A HashSet in Java stores elements without maintaining any order, providing faster operations based on hash codes. In contrast, a LinkedHashSet maintains the insertion order of elements while offering similar performance, thanks to an underlying linked list structure.

Conclusion

In this blog, we discusssed at the LinkedHashSet in the Java Collection Framework. We discussed its key features, like maintaining the order of elements while ensuring uniqueness. We also looked at the commonly used methods, such as adding, removing, and checking for elements, helping you understand how to effectively work with LinkedHashSet.

We hope that this blog has helped you enhance your knowledge about LinkedHashSet and if you would like to learn more, check out our articles on the link. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass