Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Preserve Insertion Order of Java HashSet Elements?

Improve Article
Save Article
Like Article
  • Last Updated : 07 Jan, 2021
Improve Article
Save Article
Like Article

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:

  1. Create HashSet object.
  2. Insert multiple elements in the HashSet.
  3. 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 used
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);
        }
    }
}

Output

1
2
4
13

Implementation With LinkedHashSet: (Order Maintained)

Syntax:

HashSet<String> num = new LinkedHashSet<String>();

Approach:

  1. Create a HashSet object and initialize it with the constructor of LinkedHashSet.
  2. Insert multiple elements in the HashSet.
  3. Print the HashSet.(Order maintained)

Below is the implementation of the above approach:

Java




// Preserve insertion order of Java HashSet elements
// Using LinkedHashSet
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);
        }
    }
}

Output

1
13
2
4

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!