how to get keys in Map with same sequence as they were inserted
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 {
开发者_JS百科 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());
}
}
}
I want to retrieve the keys as below
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
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.
HashMap
is a hash table. It means that the order in which keys are inserted is irrelevant, as they are not stored in this order. The moment you insert another key, the information about what was the last key is forgotten.
If you want to remember the insertion order, you need to use a different data structure.
精彩评论