如何使用与插入时相同的顺序获取Map中的键 [英] how to get keys in Map with same sequence as they were inserted
本文介绍了如何使用与插入时相同的顺序获取Map中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Map中放入一些键值,并尝试按插入时的顺序检索它们。例如下面是我的代码
I'm trying to put some key values in Map and trying to retrieve them in same sequence as they were inserted. For example below is my code
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());
}
}
}
我想要检索下面的密钥
first second third fourth fifth sixth .....
但它在我的输出中以下面的一些随机顺序显示
But it's displaying in some random order as below in my output
OUTPUT
ninth eigth fifth first sixth seventh third fourth second
推荐答案
您无法使用 HashMap
执行此操作,该操作不会在其数据中的任何位置维护插入顺序。请查看 LinkedHashMap
,专为维持此订单而设计。
You can't do this with HashMap
, which doesn't maintain an insertion order anywhere in its data. Look at LinkedHashMap
, which was designed precisely to maintain this order.
这篇关于如何使用与插入时相同的顺序获取Map中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文