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