Problem:

” HashMap does not preserve insertion order “.

HashMap is collection of Key and Value but HashMap does not give guaranty that insertion order will preserve.

i.e here we are adding data of student result from 1st to 3rd year but when we retrieve its there are possibility to change sequence.

HashMap<String, String> results = new HashMap();

results.put("FirstYear", "Pass");
results.put("SecondYear", "Fail");
results.put("ThirdYear", "Pass");

for (String result : results.keySet()) {
 System.out.println(result + " => " + results.get(result));
}

 output

ThirdYear => Pass
SecondYear => Fail
FirstYear =>Pass

when we retrieve using collages.KeySet() but its will not return set order that we insert.

Solution:

We can use LinkedHashMap for maintain insertion and retrieve order must be same:

HashMap<String, String> results = new LinkedHashMap();   // use LinkedHashMap to maintain sequence
       results.put("FirstYear", "Pass");
       results.put("SecondYear", "Fail");
       results.put("ThirdYear", "Pass");
       for (String result : results.keySet()) {
           System.out.println(result + " => " + results.get(result));
       }

 output:

FirstYear => Pass
SecondYear => Fail
ThirdYear => Pass

Refer LinkedHashMap for more details.

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *