如果我有一个用Java实现Map接口的对象,并且我希望对其中包含的每一对进行迭代,那么最有效的方法是什么?

元素的顺序是否取决于我对接口的特定映射实现?


当前回答

理论上,最有效的方法将取决于Map的实现。官方的方法是调用map.entrySet(),它返回一组map.Entry,其中每个包含一个键和一个值(Entry.getKey()和Entry.getValue())。

在特殊的实现中,使用map.keySet()、map.entrySet()或其他方法可能会有所不同。但我想不出为什么有人会这样写。最有可能的是,你所做的对绩效没有影响。

是的,顺序将取决于实现,以及(可能)插入顺序和其他难以控制的因素。

[编辑]我最初写了valueSet(),但当然entrySet()实际上是答案。

其他回答

使用Java 7

Map<String,String> sampleMap = new HashMap<>();
for (sampleMap.Entry<String,String> entry : sampleMap.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();

    /* your Code as per the Business Justification  */

}

使用Java 8

Map<String,String> sampleMap = new HashMap<>();

sampleMap.forEach((k, v) -> System.out.println("Key is :  " + k + " Value is :  " + v));

仅供参考,如果您只对映射的键/值感兴趣,而对其他键/值不感兴趣,那么也可以使用map.keySet()和map.values()。

Map上的一个有效迭代解决方案是从Java5到Java7的for循环。这里是:

for (String key : phnMap.keySet()) {
    System.out.println("Key: " + key + " Value: " + phnMap.get(key));
}

在Java8中,可以使用lambda表达式对Map进行迭代。这是一个增强的forEach

phnMap.forEach((k,v) -> System.out.println("Key: " + k + " Value: " + v));

如果要为lambda编写条件,可以这样编写:

phnMap.forEach((k,v)->{
    System.out.println("Key: " + k + " Value: " + v);
    if("abc".equals(k)){
        System.out.println("Hello abc");
    }
});

在地图上迭代的典型代码是:

Map<String,Thing> map = ...;
for (Map.Entry<String,Thing> entry : map.entrySet()) {
    String key = entry.getKey();
    Thing thing = entry.getValue();
    ...
}

HashMap是规范映射实现,不做任何保证(或者,如果不对其执行任何变异操作,则不应更改顺序)。SortedMap将根据键的自然顺序或Comparator(如果提供)返回条目。LinkedHashMap将按照插入顺序或访问顺序返回条目,具体取决于它的构造方式。EnumMap以键的自然顺序返回条目。

(更新:我认为这不再是真的。)注意,IdentityHashMap entrySet迭代器目前有一个特殊的实现,它为entrySet中的每个项返回相同的Map.Entry实例!然而,每次新迭代器推进Map.Entry时都会更新。

有几种方法可以迭代地图。

下面是通过在map中存储一百万个键值对并将在map中进行迭代,对map中存储的公共数据集的性能进行比较。

1) 在每个循环中使用entrySet()

for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
    entry.getKey();
    entry.getValue();
}

50毫秒

2) 在每个循环中使用keySet()

for (String key : testMap.keySet()) {
    testMap.get(key);
}

76毫秒

3) 使用entrySet()和迭代器

Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator();
while(itr1.hasNext()) {
    Map.Entry<String,Integer> entry = itr1.next();
    entry.getKey();
    entry.getValue();
}

50毫秒

4) 使用keySet()和迭代器

Iterator itr2 = testMap.keySet().iterator();
while(itr2.hasNext()) {
    String key = itr2.next();
    testMap.get(key);
}

75毫秒

我已经提到了这个链接。