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
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.
Duplicate keys are not allowed in 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With