A LinkedHashSet is an ordered form of HashSet that maintains the iteration order. A normal HashSet has no iteration order whereas, in a LinkedHashSet, elements are sorted according to their insertion order. This class extends the HashSet class.
LinkedHashSet<data-type> LnkdHashSet = new LinkedHashSet<data-type>();
By default, Java provides some useful helper functions with the HashSet class. Let’s look at some of them in detail:
As the name suggests, this function adds elements to the LinkedHashSet (provided that they do not exist in the HashSet prior to insertion).
Removes a particular object from the LinkedHashSet.
Removes all of the elements from the LinkedHashSet.
Checks whether or not the specific element is present in the LinkedHashSet.
Returns the number of elements currently present in the LinkedHashSet.
Checks whether or not the LinkedHashSet is empty.
Let’s take a look at a simple comparison between a HashSet and a LinkedHashSet. When we insert {1, 2, 4, 3} in the HashSet, it sorts the elements and prints them in a sorted order ( i.e., {1, 2, 3, 4} ). Whereas, in the LinkedHashSet, the elements are printed in the insertion order {1, 2, 4, 3}.
import java.util.HashSet;class Main {public static void main(String[] args) {// Creating HashSet to store String valuesHashSet<Integer> hash_set = new HashSet<Integer>();// Adding elements into HashSet usind add()hash_set.add(1);hash_set.add(2);hash_set.add(4);hash_set.add(3);// Displaying the HashSet UnorderedSystem.out.println("HashSet: " + hash_set);// Extracting size of HashSetint size = hash_set.size();System.out.printf("Size of HashSet is: %d \n", size);// Remove an elementhash_set.remove(4);// Display HashSet after removalSystem.out.println("HashSet after removal: " + hash_set);}}
Free Resources