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

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


当前回答

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

其他回答

Java 8

我们得到了接受lambda表达式的forEach方法。我们也有流API。考虑一张地图:

Map<String,String> sample = new HashMap<>();
sample.put("A","Apple");
sample.put("B", "Ball");

在关键点上重复:

sample.keySet().forEach((k) -> System.out.println(k));

遍历值:

sample.values().forEach((v) -> System.out.println(v));

遍历条目(使用forEach和Streams):

sample.forEach((k,v) -> System.out.println(k + ":" + v)); 
sample.entrySet().stream().forEach((entry) -> {
            Object currentKey = entry.getKey();
            Object currentValue = entry.getValue();
            System.out.println(currentKey + ":" + currentValue);
        });

流的优点是,如果我们需要,它们可以很容易地并行化。我们只需要使用parallelStream()代替上面的stream()。

forEachOrdered与forEach的流?forEach不遵循遭遇顺序(如果已定义),本质上是非确定性的,正如forEachOrdered一样。因此forEach不保证订单会被保留。还要查看此项了解更多信息。

package com.test;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("ram", "ayodhya");
        map.put("krishan", "mathura");
        map.put("shiv", "kailash");

        System.out.println("********* Keys *********");
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
        }

        System.out.println("********* Values *********");
        Collection<String> values = map.values();
        for (String value : values) {
            System.out.println(value);
        }

        System.out.println("***** Keys and Values (Using for each loop) *****");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out.println("***** Keys and Values (Using while loop) *****");
        Iterator<Entry<String, String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) entries
                    .next();
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out
                .println("** Keys and Values (Using java 8 using lambdas )***");
        map.forEach((k, v) -> System.out
                .println("Key: " + k + "\t value: " + v));
    }
}

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

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

在Java 1.4中尝试:

for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){

  Entry entry = (Entry) entries.next();

  System.out.println(entry.getKey() + "/" + entry.getValue());

  //...
}

迭代地图非常简单。

for(Object key: map.keySet()){
   Object value= map.get(key);
   //Do your stuff
}

例如,您有一个Map<String,int>数据;

for(Object key: data.keySet()){
  int value= data.get(key);
}