Query explained:
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?
How to iterate over a Map in Java?
The following code will help:
Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
On Java 10+:
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:
1). Using iterator and Map.Entry
long i = 0;
Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Integer> pair = it.next();
i += pair.getKey() + pair.getValue();
}
2). Using foreach and Map.Entry
long i = 0;
for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
i += pair.getKey() + pair.getValue();
}
3). Using forEach from Java 8
final long[] i = {0};
map.forEach((k, v) -> i[0] += k + v);
4). Using keySet and foreach
long i = 0;
for (Integer key : map.keySet()) {
i += key + map.get(key);
}
5). Using keySet and iterator
long i = 0;
Iterator<Integer> itr2 = map.keySet().iterator();
while (itr2.hasNext()) {
Integer key = itr2.next();
i += key + map.get(key);
}
6). Using for and Map.Entry
long i = 0;
for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {
Map.Entry<Integer, Integer> entry = entries.next();
i += entry.getKey() + entry.getValue();
}
7). Using the Java 8 Stream API
final long[] i = {0};
map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());
8). Using the Java 8 Stream API parallel
final long[] i = {0};
map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());
9). Using IterableMap of Apache Collections
long i = 0;
MapIterator<Integer, Integer> it = iterableMap.mapIterator();
while (it.hasNext()) {
i += it.next() + it.getValue();
}
10). Using MutableMap of Eclipse (CS) collections
final long[] i = {0};
mutableMap.forEachKeyValue((key, value) -> {
i[0] += key + value;
});
Perfomance tests (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)
1). For a small map (100 elements), score 0.308 is the best
Benchmark Mode Cnt Score Error Units
test3_UsingForEachAndJava8 avgt 10 0.308 ± 0.021 µs/op
test10_UsingEclipseMap avgt 10 0.309 ± 0.009 µs/op
test1_UsingWhileAndMapEntry avgt 10 0.380 ± 0.014 µs/op
test6_UsingForAndIterator avgt 10 0.387 ± 0.016 µs/op
test2_UsingForEachAndMapEntry avgt 10 0.391 ± 0.023 µs/op
test7_UsingJava8StreamApi avgt 10 0.510 ± 0.014 µs/op
test9_UsingApacheIterableMap avgt 10 0.524 ± 0.008 µs/op
test4_UsingKeySetAndForEach avgt 10 0.816 ± 0.026 µs/op
test5_UsingKeySetAndIterator avgt 10 0.863 ± 0.025 µs/op
test8_UsingJava8StreamApiParallel avgt 10 5.552 ± 0.185 µs/op
2). For a map with 10000 elements, score 37.606 is the best
Benchmark Mode Cnt Score Error Units
test10_UsingEclipseMap avgt 10 37.606 ± 0.790 µs/op
test3_UsingForEachAndJava8 avgt 10 50.368 ± 0.887 µs/op
test6_UsingForAndIterator avgt 10 50.332 ± 0.507 µs/op
test2_UsingForEachAndMapEntry avgt 10 51.406 ± 1.032 µs/op
test1_UsingWhileAndMapEntry avgt 10 52.538 ± 2.431 µs/op
test7_UsingJava8StreamApi avgt 10 54.464 ± 0.712 µs/op
test4_UsingKeySetAndForEach avgt 10 79.016 ± 25.345 µs/op
test5_UsingKeySetAndIterator avgt 10 91.105 ± 10.220 µs/op
test8_UsingJava8StreamApiParallel avgt 10 112.511 ± 0.365 µs/op
test9_UsingApacheIterableMap avgt 10 125.714 ± 1.935 µs/op
3). For a map with 100000 elements, score 1184.767 is the best
Benchmark Mode Cnt Score Error Units
test1_UsingWhileAndMapEntry avgt 10 1184.767 ± 332.968 µs/op
test10_UsingEclipseMap avgt 10 1191.735 ± 304.273 µs/op
test2_UsingForEachAndMapEntry avgt 10 1205.815 ± 366.043 µs/op
test6_UsingForAndIterator avgt 10 1206.873 ± 367.272 µs/op
test8_UsingJava8StreamApiParallel avgt 10 1485.895 ± 233.143 µs/op
test5_UsingKeySetAndIterator avgt 10 1540.281 ± 357.497 µs/op
test4_UsingKeySetAndForEach avgt 10 1593.342 ± 294.417 µs/op
test3_UsingForEachAndJava8 avgt 10 1666.296 ± 126.443 µs/op
test7_UsingJava8StreamApi avgt 10 1706.676 ± 436.867 µs/op
test9_UsingApacheIterableMap avgt 10 3289.866 ± 1445.564 µs/op
Graphs (performance tests depending on map size)

Table (perfomance tests depending on map size)
100 600 1100 1600 2100
test10 0.333 1.631 2.752 5.937 8.024
test3 0.309 1.971 4.147 8.147 10.473
test6 0.372 2.190 4.470 8.322 10.531
test1 0.405 2.237 4.616 8.645 10.707
test2 0.376 2.267 4.809 8.403 10.910
test7 0.473 2.448 5.668 9.790 12.125
test9 0.565 2.830 5.952 13.220 16.965
test4 0.808 5.012 8.813 13.939 17.407
test5 0.810 5.104 8.533 14.064 17.422
test8 5.173 12.499 17.351 24.671 30.403
How to iterate over each entry in a Java Map?Answer #3:
In Java 8 you can do it cleanly and fast using the new lambdas features:
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));
The type of k
and v
will be inferred by the compiler and there is no need to use Map.Entry
anymore.
Easy-peasy!
Answer #4:
Typical code for iterating over a map is:
Map<String,Thing> map = ...;
for (Map.Entry<String,Thing> entry : map.entrySet()) {
String key = entry.getKey();
Thing thing = entry.getValue();
...
}
HashMap
is the canonical map implementation and doesn’t make guarantees (or though it should not change the order if no mutating operations are performed on it). SortedMap
will return entries based on the natural ordering of the keys, or a Comparator
, if provided. LinkedHashMap
will either return entries in insertion-order or access-order depending upon how it has been constructed. EnumMap
returns entries in the natural order of keys.
(Update: I think this is no longer true.) Note, IdentityHashMap
entrySet
iterator currently has a peculiar implementation that returns the same Map.Entry
instance for every item in the entrySet
! However, every time a new iterator advances the Map.Entry
is updated.
How to iterate over a HashMap in Java? Answer #5:
There are several ways of iterating over a Map
in Java. Let’s go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (HashMap
, TreeMap
, LinkedHashMap
, Hashtable
, etc.)
Method #1: Iterating over entries using a For-Each loop.
This is the most common method and is preferable in most cases. It should be used if you need both map keys and values in the loop.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Note that the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a For-Each loop will throw NullPointerException
if you try to iterate over a map that is null, so before iterating you should always check for null references.
Method #2: Iterating over keys or values using a For-Each loop.
If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// Iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
// Iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
This method gives a slight performance advantage over entrySet
iteration (about 10% faster) and is more clean.
Method #3: Iterating using Iterator.
Using Generics:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
You can also use the same technique to iterate over keySet
or values.
This method might look redundant, but it has its own advantages. First of all, it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove()
. If you try to do this during For-Each iteration you will get “unpredictable results” according to Javadoc.
From a performance point of view, this method is equal to a For-Each iteration.
Method #4: Iterating over keys and searching for values (inefficient).
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
This might look like a cleaner alternative for method #1, but in practice, it is pretty slow and inefficient as getting values by a key might be time-consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.
Conclusion:
If you need only keys or values from the map, use method #2. If you are stuck with an older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #3. Otherwise use method #1.
Answer #6:
Example of using iterator and generics:
Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
// ...
}
Answer #7:
This is a two part question:
How to iterate over the entries of a Map – This has been answered that perfectly in above answers.
What is the order of iteration – if you are just using Map
, then strictly speaking, there are no ordering guarantees. So you shouldn’t really rely on the ordering given by any implementation. However, the SortedMap
interface extends Map
and provides exactly what you are looking for – implementations will aways give a consistent sort order.
NavigableMap
is another useful extension – this is a SortedMap
with additional methods for finding entries by their ordered position in the key set. So potentially this can remove the need for iterating in the first place – you might be able to find the specific entry
you are after using the higherEntry
, lowerEntry
, ceilingEntry
, or floorEntry
methods. The descendingMap
method even gives you an explicit method of reversing the traversal order.
To summarize:
There are several ways to iterate over map.
Here is a 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);
}
Hope you learned something from this post.
Follow Programming Articles for more!