📜  Java HashMap中如何维护元素的插入顺序?

📅  最后修改于: 2022-05-13 01:55:50.039000             🧑  作者: Mango

Java HashMap中如何维护元素的插入顺序?

当元素由于散列而从 HashMap 获取时,它们插入的顺序在检索时不会得到维护。我们可以使用 LinkedHashMap 实现给定的任务。 LinkedHashMap 类实现了一个双向链表,以便它可以遍历所有元素。

例子:

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}

句法:

它使用原始 Map 对象中指定的相同映射创建 LinkedHashMap 类的对象。

此处不维护订单: HashMap 实现:

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 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 entry :
             hm.entrySet()) {
            System.out.println(entry.getKey() + " => "
                               + ": " + entry.getValue());
        }
    }
}


Java
// Java Program to maintain insertion order
// of the elements in HashMap
  
// LinkedHashMap
import java.io.*;
import java.util.*;
class GFG {
  
    public static void main(String args[])
    {
  
        // creating a hashmap
        HashMap 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 entry :
             hm.entrySet()) {
            System.out.println(entry.getKey() + " => "
                               + ": " + entry.getValue());
        }
    }
}


输出
Iterate over original HashMap
01 => : aaaaaaa
02 => : kkkkkkk
03 => : bbbbbbb
04 => : zzzzzzz

这里,HashMap 的原始插入顺序是 [01, 03, 04, 02],但输出的是不同的 [01, 02, 03, 04]。它没有保持元素的原始插入顺序。

订单维护在这里: LinkedHashMap 实现

Java

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