简体   繁体   中英

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?

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

You can't a hashmap has no internal order

You will have to use another implementation of Map

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM