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

Jav*_*eek 23 java

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

import java.util.*;
import java.util.Map.Entry;

public class HashMaptoArrayExample {

    public static void main(String args[])

    {
   Map<String,Integer> map=  new HashMap<String,Integer>();

   // 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());
       }

    }
}
Run Code Online (Sandbox Code Playgroud)

我想检索如下的密钥

first second third fourth fifth sixth .....
Run Code Online (Sandbox Code Playgroud)

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

OUTPUT

ninth eigth fifth first sixth seventh third fourth second
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 60

您无法执行此操作HashMap,因为它不会在其数据中的任何位置维护插入顺序.看看LinkedHashMap,这是为了维持这种秩序而精心设计的.