I have an object with Map interface in java, so i would like to know which is the best way to iterate over the items in a HashMap
?
Explain in more details if possible, thanks
There are many ways to do it using for loop or iterator, here are the few ways suppose that we have a List collection as follows:
HashMap<String, String> userMap = new HashMap<String, String>();
userMap.put("1", "John");
userMap.put("2", "Stuart");
userMap.put("3", "Scott");
then you can loop through it using the Various method as below
First Method, using Iterator
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
Output will be as given below
1 : John
2 : Stuart
3 : Scott
above method may look redundant, but it has its some advantages. First thing, 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
it
.remove()
, which you can't try to do in for-each loop, it may produce unexpected results
Second method using For 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.
for (Map.Entry<String, String> entry : userMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+ " : "+ value);
}
//Output
//1 : John Doe
//2 : Stuart Little
//3 : Scott Tiger
Third Method For-each loop
// Iterating over keys only
for (String key : userMap.keySet()) {
System.out.println("Key = " + key);
}
// Iterating over values only
for (String value : userMap.values()) {
System.out.println("Value = " + value);
}
Output
Key = 1
Key = 2
Key = 3
Value = John
Value = Stuart
Value = Scott
Above method has little bit performance advantage over entrySet
iteration and it's cleaner
Complete code for first method would be as below
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MyClass {
public static void main(String args[]) {
HashMap<String, String> userMap = new HashMap<String, String>();
userMap.put("1", "John");
userMap.put("2", "Stuart");
userMap.put("3", "Scott");
//Method 1
Iterator it = userMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
}
In Java 10+ you can iterate
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
In Java 8, you can do it , clean and fast using the new lambdas features:
Map<String,String> map = new HashMap<>();
map.put("YouKey", "YourValue");
map.forEach( (k,v) -> [do something with key and value] );
// such as
map.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));
That's it.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly