Question: If I have an object implementing the `Map` interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?

Will the ordering of elements depend on the specific map implementation that I have for the interface?

Answer: 
```java
Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

```

On Java 10+:

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

```
There are several ways to iterate over map.

Here is comparison of their performances for a common data set stored in map by storing a million key value pairs in map and will iterate over map.

**1) Using `entrySet()` in for each loop**

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

```

*50 milliseconds*

**2) Using `keySet()` in for each loop**

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

```

*76 milliseconds*

**3) Using `entrySet()` and iterator**

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

```

*50 milliseconds*

**4) Using `keySet()` and iterator**

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

```

*75 milliseconds*

I have referred [`this link`](http://howtodoinjava.com/2013/04/01/performance-comparison-of-different-ways-to-iterate-over-hashmap/).