如何从 iterator() 中获取按正确顺序排列的元素
这是我的代码,用于将数据存储到 HashMap 并使用迭代器显示数据,
public static void main(String args[]) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("aaa", "111");
hm.put("bbb", "222");
hm.put("ccc", "333");
hm.put("ddd", "444");
hm.put("eee", "555");
hm.put("fff", "666");
Iterator iterator = hm.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String val = hm.get(key);
System.out.println(key + " " + val);
}
}
但它没有按照我存储的顺序显示。有人可以告诉我我哪里出错了吗?如何获取订单中的元素?
Here is my code to store the data into HashMap and display the data using iterator
public static void main(String args[]) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("aaa", "111");
hm.put("bbb", "222");
hm.put("ccc", "333");
hm.put("ddd", "444");
hm.put("eee", "555");
hm.put("fff", "666");
Iterator iterator = hm.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String val = hm.get(key);
System.out.println(key + " " + val);
}
}
But it is not displaying in the order in which I stored. Could someone please tell me where am I going wrong? How can I get the elements in the order?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
HashMap 没有保证顺序:
使用 LinkedHashMap。
A HashMap has no guaranteed order:
Use a LinkedHashMap.
您需要使用 LinkedHashMap 因为它维护其条目的顺序,与 HashMap 不同。
来自javadoc:
You need to use a LinkedHashMap because it maintains ordering of its entries, unlike HashMap.
From the javadocs:
HashMap 不保持我们放入数据的顺序。因此您可以遵循 LinkedHashMap。它保持我们放入数据的顺序。LinkedHashMap 的使用方式与 HashMap 相同。
//类似地,您也可以使用迭代器来访问数据。它将按照您添加的顺序显示 dfata。
HashMap does not keep order in which we put data into it.So You may follow LinkedHashMap instead.It keeps the order in which we put data.LinkedHashMap can be used same as HashMap.
//similarly you can use iterator to access data too.It will display dfata in order in which you added to it.
原因是HashMap和HashSet不保证存储值的顺序。元素的位置取决于内表的大小和键的 hashCode。
如果您想按某种顺序加载数据,则需要对键/或值进行排序。例如,您可以将条目集合 (Map.entrySet()) 放入列表中并按您想要的任何条件进行排序。或者您可以使用 SortedMap(例如 TreeMap)来存储对象。
The reason is HashMap and HashSet doesn't guarantee the order of the stored values. Position of the elements will depends on the size of the internal table and hashCode of the key.
If you want to load your data in some order you need to sort keys/or values. For example you can put collections of the entries (Map.entrySet()) to the list and sort by any criteria you want. Or you can use SortedMap (TreeMap for example) to store your objects.