How to Preserve Insertion Order of Java HashSet Elements?
When elements get from the HashSet due to hashing the order they inserted is not maintained while retrieval. HashSet stores the elements by using a mechanism called hashing. We can achieve the given task using LinkedHashSet. The LinkedHashSet class implements a doubly-linked list so that it can traverse through all the elements.
Example:
Input : HashSetInput = {c, a, b}
Output: HashSetPrint = {c, a, b}
Input : HashSetInput = {"first", "second"}
Output: HashSetPrint = {"first", "second"}
Implementation With HashSet: (Order Not Maintained)
Syntax:
HashSet<String> num = new HashSet<String>();
Approach:
- Create HashSet object.
- Insert multiple elements in the HashSet.
- Print the HashSet.(Order not maintained)
Below is the implementation of the above approach:
Java
import java.util.HashSet;
import java.util.Set;
public class PreserveHashSetOrderExample {
public static void main(String[] args)
{
Set<Integer> hSetNumbers = new HashSet<Integer>();
hSetNumbers.add( 1 );
hSetNumbers.add( 13 );
hSetNumbers.add( 2 );
hSetNumbers.add( 4 );
for (Integer number : hSetNumbers) {
System.out.println(number);
}
}
}
|
Implementation With LinkedHashSet: (Order Maintained)
Syntax:
HashSet<String> num = new LinkedHashSet<String>();
Approach:
- Create a HashSet object and initialize it with the constructor of LinkedHashSet.
- Insert multiple elements in the HashSet.
- Print the HashSet.(Order maintained)
Below is the implementation of the above approach:
Java
import java.util.LinkedHashSet;
import java.util.Set;
public class PreserveHashSetOrderExample {
public static void main(String[] args)
{
Set<Integer> setNumbers
= new LinkedHashSet<Integer>();
setNumbers.add( 1 );
setNumbers.add( 13 );
setNumbers.add( 2 );
setNumbers.add( 4 );
for (Integer number : setNumbers) {
System.out.println(number);
}
}
}
|
Last Updated :
07 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...