Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get keys in Map with same sequence as they were inserted

Tags:

java

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

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 
like image 425
JavaGeek Avatar asked Jan 27 '11 11:01

JavaGeek


People also ask

How do I find duplicate keys on a map?

Keys are unique once added to the HashMap , but you can know if the next one you are going to add is already present by querying the hash map with containsKey(..) or get(..) method.

Can maps have repeated keys?

Duplicate keys are not allowed in a Map.

How do you keep an insertion order on a map?

This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.

Can 2 keys have same value in map?

A map will always return the Object tied to that key, the value from the entry. Map performance degrades rapidly if hashCode() returns the same (or similar) values for different keys.


2 Answers

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.

like image 53
Jon Skeet Avatar answered Oct 12 '22 00:10

Jon Skeet


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.

like image 31
Ilya Kogan Avatar answered Oct 12 '22 02:10

Ilya Kogan