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?
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
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