![](/img/trans.png)
[英]When iterating through a HashMap with Integer keys, will it always return keys in ascending order?
[英]When using a HashMap are values and keys guaranteed to be in the same order when iterating?
当我迭代值或键时它们会相关吗? 第二个键会映射到第二个值吗?
不,不一定。 为此,您应该使用entrySet()。iterator()。 使用此迭代器,您将遍历Map中的所有Map.Entry对象,并可以访问每个键和关联的值。
使用@Cuchullain提到的entrySet:
Map<String, String> map = new HashMap<String, String>();
// populate hashmap
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// your code here
}
您希望将此LinkedHashMap用于可预测的迭代顺序
public class Test {
public static void main(String[] args) {
HashMap <String,String> hashmap = new HashMap<String,String>();
hashmap.put("one", "1");
hashmap.put("two", "2");
hashmap.put("three", "3");
hashmap.put("four", "4");
hashmap.put("five", "5");
hashmap.put("six", "6");
Iterator <String> keyIterator = hashmap.keySet().iterator();
Iterator <String> valueIterator = hashmap.values().iterator();
while(keyIterator.hasNext()) {
System.out.println("key: "+keyIterator.next());
}
while(valueIterator.hasNext()) {
System.out.println("value: "+valueIterator.next());
}
}
}
key: two
key: five
key: one
key: three
key: four
key: six
value: 2
value: 5
value: 1
value: 3
value: 4
value: 6
values()和keySet()都委托给entrySet()迭代器,因此它们将以相同的顺序返回。 但是像Alex说的那样直接使用entrySet()迭代器要好得多。
我同意pmac72。 不要假设您将从无序集合中获取有序值或键。 如果它不时地工作它只是纯粹的危险。 如果要保留订单,请使用LinkedHashMap或TreeMap或commons集合OrderedMap。
这个问题起初让我困惑,但@Matt为我清理了它。
考虑使用entrySet()方法,该方法返回Map上具有键值对的集合。
Map<Integer, Integer> a = new HashMap<Integer, Integer>(2);
a.put(1, 2);
a.put(2, 3);
for (Map.Entry<Integer, Integer> entry : a.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
这输出:
1 => 2
2 => 3
3 => 3
我是第二个@basszero。 而
for (Map.Entry<Integer, Integer> entry : a.entrySet())
我会发现使用自动执行此操作的数据结构会更好。 现在,您可以“正常”迭代
HashMap的keySet方法返回一个Set,它不保证顺序。
HashMap的values()方法返回一个Collection,它不保证顺序。
也就是说,问题是“它们是否会相关”,所以技术上答案可能是,但不要依赖它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.