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
// Java Program to maintain insertion order// of the elements in HashMap  // Using HashMap (Order not maintain)import java.io.*;import java.util.*;class GFG {      public static void main(String args[])    {          // creating a hashmap        HashMap<String, String> hm = new HashMap<>();          // putting elements        hm.put("01", "aaaaaaa");        hm.put("03", "bbbbbbb");        hm.put("04", "zzzzzzz");        hm.put("02", "kkkkkkk");          System.out.println("Iterate over original HashMap");                // printing hashmap        for (Map.Entry<String, String> entry :             hm.entrySet()) {            System.out.println(entry.getKey() + " => "                               + ": " + entry.getValue());        }    }} |
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
// Java Program to maintain insertion order// of the elements in HashMap  // LinkedHashMapimport java.io.*;import java.util.*;class GFG {      public static void main(String args[])    {          // creating a hashmap        HashMap<String, String> hm = new LinkedHashMap<>();          // putting elements        hm.put("01", "aaaaaaa");        hm.put("03", "bbbbbbb");        hm.put("04", "zzzzzzz");        hm.put("02", "kkkkkkk");          // printing LinkedHashMap        System.out.println("Iterate over LinkedHashMap");        for (Map.Entry<String, String> entry :             hm.entrySet()) {            System.out.println(entry.getKey() + " => "                               + ": " + entry.getValue());        }    }} |
Iterate over LinkedHashMap 01 => : aaaaaaa 03 => : bbbbbbb 04 => : zzzzzzz 02 => : kkkkkkk
