如何使用与插入时相同的顺序获取Map中的键

我试图在Map中放入一些键值,并尝试以与插入时相同的顺序检索它们。 例如下面是我的代码

import java.util.*; import java.util.Map.Entry; public class HashMaptoArrayExample { public static void main(String args[]) { Map map= new HashMap(); // put some values into map map.put("first",1); map.put("second",2); map.put("third",3); map.put("fourth",4); map.put("fifth",5); map.put("sixth",6); map.put("seventh",7); map.put("eighth",8); map.put("ninth",9); Iterator iterator= map.entrySet().iterator(); while(iterator.hasNext()) { Entry entry =(Entry)iterator.next(); System.out.println(" entries= "+entry.getKey().toString()); } } } 

我想检索如下的密钥

 first second third fourth fifth sixth ..... 

但它在我的输出中以一些随机顺序显示如下

 OUTPUT ninth eigth fifth first sixth seventh third fourth second 

您无法使用HashMap执行此操作, HashMap不会在其数据中的任何位置维护插入顺序。 查看LinkedHashMap ,它专为维护此顺序而设计。

HashMap是一个哈希表。 这意味着插入密钥的顺序无关紧要,因为它们不按此顺序存储。 插入另一个密钥的那一刻,忘记了最后一个密钥的信息。

如果要记住插入顺序,则需要使用不同的数据结构。