Do you think IIT Guwahati certified course can help you in your career?
No
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.
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:
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).
LinkedHashSet lh=new LinkedHashSet(int initialCapacity); // A LinkedHashSet with customized capacity is created.
LinkedHashSet h=new LinkedHashSet(int initialCapacity, float load factor); //A LinkedHashSet is created with a customized initial capacity and load factor.
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
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
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
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
Adding Elements: Use the add() method to add elements. Duplicate entries are ignored.
Removing Elements: Use the remove() method to remove a specific element.
Checking Existence: Use the contains() method to verify if a particular element is present.
Size: Use the size() method to get the number of elements in the set.
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!