Which is the best method to iterate through the hashmap in java?


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


Asked by:- Sam
0
: 3072 At:- 11/21/2017 1:21:46 PM
java hashmap collections lopping hashmap in java different ways of iterating hashmap







2 Answers
profileImage Answered by:- jaiprakash

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
    }


}
}
1
At:- 11/22/2017 7:16:01 AM
thanks 0
By : Sam - at :- 11/28/2017 1:02:49 PM


profileImage Answered by:- vikas_jk

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.

0
At:- 5/11/2022 3:10:48 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use