How to Maintain Insertion Order of the Elements in Java HashMap?
Last Updated :
04 Jan, 2021
When elements get from the HashMap due to hashing the order they inserted is not maintained while retrieval. We can achieve the given task using LinkedHashMap. The LinkedHashMap class implements a doubly-linked list so that it can traverse through all the elements.
Example:
Input : HashMapInput = {c=6, a=1, b=2}
Output: HashMapPrint = {c=6, a=1, b=2}
Input : HashMapInput = {"first"=1, "second"=3}
Output: HashMapPrint = {"first"=1, "second"=3}
Syntax:
public LinkedHashMap(Map m)
It creates an object of the LinkedHashMap class with the same mappings specified in the original Map object.
Order Not Maintain Here: HashMap Implementation:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[])
{
HashMap<String, String> hm = new HashMap<>();
hm.put( "01" , "aaaaaaa" );
hm.put( "03" , "bbbbbbb" );
hm.put( "04" , "zzzzzzz" );
hm.put( "02" , "kkkkkkk" );
System.out.println( "Iterate over original HashMap" );
for (Map.Entry<String, String> entry :
hm.entrySet()) {
System.out.println(entry.getKey() + " => "
+ ": " + entry.getValue());
}
}
}
|
Output
Iterate over original HashMap
01 => : aaaaaaa
02 => : kkkkkkk
03 => : bbbbbbb
04 => : zzzzzzz
Here, the original insertion order of HashMap is [01, 03, 04, 02], but the output is different [01, 02, 03, 04]. It did not maintain the original insertion order of the elements.
Order Maintain Here: LinkedHashMap implementation
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[])
{
HashMap<String, String> hm = new LinkedHashMap<>();
hm.put( "01" , "aaaaaaa" );
hm.put( "03" , "bbbbbbb" );
hm.put( "04" , "zzzzzzz" );
hm.put( "02" , "kkkkkkk" );
System.out.println( "Iterate over LinkedHashMap" );
for (Map.Entry<String, String> entry :
hm.entrySet()) {
System.out.println(entry.getKey() + " => "
+ ": " + entry.getValue());
}
}
}
|
Output
Iterate over LinkedHashMap
01 => : aaaaaaa
03 => : bbbbbbb
04 => : zzzzzzz
02 => : kkkkkkk
Share your thoughts in the comments
Please Login to comment...