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
// Preserve insertion order of Java HashSet elements// Order not maintained because HashSet usedimport 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);Â Â Â Â Â Â Â Â }Â Â Â Â }} |
1 2 4 13
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
// Preserve insertion order of Java HashSet elements// Using LinkedHashSetimport 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);        }    }} |
1 13 2 4
