java - 如何按顺序遍历地图

java - how to iterate through maps in order

这是代码:

for(String key : mymap.stringPropertyNames()) {
//mycode
}

这工作正常,但我注意到我以随机顺序获得了我需要的值,有没有办法使用特定顺序循环遍历地图?

编辑:Mymap 是一个 properties 对象。

这是因为您使用的 Map 没有像 HashMap

这样的排序

[...] This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.


除此之外,您可以使用一些具体的实现,例如:

TreeMap:

The map is sorted according to the natural ordering of its keys or by a Comparator provided at map creation time, depending on which constructor is used.

LinkedHashMap如果你需要没有重复...

Hash table and linked list implementation of the Map interface, with predictable iteration order.

如果您想要可预测的迭代顺序(插入顺序),请使用 LinkedHashMap

如果要对元素进行排序,则需要使用 TreeMap , in this case the Keys need to implement Comparable 界面

要么将 Map 实现更改为支持排序的实现之一,要么在遍历它们之前对键进行排序。不过我有点困惑,通常是通过 keySet 方法获取地图的键。我不熟悉 stringPropertyNames 但如果它是一个 Map 你应该能够做类似的事情(未经测试的代码):

List keys = new ArrayList(mymap.keySet())
Collections.sort(keys)
for ( String key : keys ) {
    [...]
}