Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the hashmap values from the order they inserted into the hashmap

I have a HashMap which have strings as key and value,

HashMap dataSet = new HashMap();

dataSet.put("A1", "Aania");
dataSet.put("X1", "Abatha");
dataSet.put("C1", "Acathan");
dataSet.put("S1", "Adreenas");

I want to print it as the order it is inserted into the HashMap, So the output should be like,

A1, Aania
X1, Abatha
C1, Acathan
S1, Adreenas  

Can anyone please tell me how to do this?

like image 534
Roshanck Avatar asked Aug 18 '12 14:08

Roshanck


1 Answers

You can use a LinkedHashMap instead, which will preserve the insertion order. You can't do what you ask for with a standard HashMap.

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).

So the first line of your code would become:

Map dataSet = new LinkedHashMap();

You might also want to add generics as a good practice:

Map<String, String> dataSet = new LinkedHashMap<String, String>();
like image 130
assylias Avatar answered Oct 06 '22 01:10

assylias