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

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


当前回答

使用Java 8:

map.entrySet().forEach(entry -> System.out.println(entry.getValue()));

其他回答

从Java10开始,您可以使用局部变量推理(也称为“var”)来减少许多现有答案的臃肿。例如:

for (var entry : map.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

是的,许多人都认为这是迭代地图的最佳方式。

但如果映射为空,则有可能引发nullpointerexception。别忘了输入null。签入。

                                                 |
                                                 |
                                         - - - -
                                       |
                                       |
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
}

使用Java 8:

map.entrySet().forEach(entry -> System.out.println(entry.getValue()));

使用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));

在Java 8中,您可以使用新的lambdas功能快速、干净地完成任务:

 Map<String,String> map = new HashMap<>();
 map.put("SomeKey", "SomeValue");
 map.forEach( (k,v) -> [do something with key and value] );

 // such as
 map.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));

k和v的类型将由编译器推断,不再需要使用Map.Entry。

小菜一碟