简体   繁体   English

如何按照插入哈希表中的顺序打印哈希表值

[英]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,其中包含字符串作为键和值,

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, 我想按将其插入到HashMap中的顺序进行打印,因此输出应为:

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. 您可以改用LinkedHashMap ,它将保留插入顺序。 You can't do what you ask for with a standard HashMap . 使用标准的HashMap不能满足您的要求。

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. 此实现与HashMap的不同之处在于,它维护贯穿其所有条目的双向链接列表。 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 您将不得不使用Map的另一种实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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