Saturday, November 22, 2025
HomeLanguagesJavaHow to Preserve Insertion Order of Java HashSet Elements?

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:

  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
RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6851 POSTS0 COMMENTS