Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap returns value in non sequential order

Tags:

java

hashmap

map

I am inserting four values with different keys in a HashMap. Code Snippet :

HashMap<Integer, String> choice = new HashMap<Integer, String>();

choice.put(1, "1917");
choice.put(2, "1791");
choice.put(3, "1902");
choice.put(4, "1997");

But when I am printing that map values,it returns a result something like :

{4=1997, 1=1917, 2=1791, 3=1902}

How can I get the map values in a sequential order the way I have put/inserted?

like image 305
Rajhrita Avatar asked Nov 30 '22 05:11

Rajhrita


1 Answers

You can use a LinkedHashMap instead, which will keep the insertion order:

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

You can modify your code like this:

Map<Integer, String> choice = new LinkedHashMap<Integer, String>();

//rest of the code is the same
like image 55
assylias Avatar answered Dec 02 '22 20:12

assylias