What is the best way to iterate objects in a HashMap?

What is the best way to iterate objects in a HashMap in Java in order to have access to the key and value of each entry?

Author: Marco Souza, 2013-12-11

5 answers

I like to use the loop for because the code gets leaner:

for (Map.Entry<String,Integer> pair : myHashMap.entrySet()) {
    System.out.println(pair.getKey());
    System.out.println(pair.getValue());
}
 48
Author: Ecil, 2019-11-11 23:35:41

Using method entrySet(), Example:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}

Source: https://stackoverflow.com/questions/1066589/java-iterate-through-hashmap

Edit.: According to the tip of (Vitor de Mario) there is a brief explanation between the difference of entrySet() and LinkedHashMap<K,V>.

entrySet() does not guarantee the iteration order, since LinkedHashMap<K,V> will iterate exactly in the order it is presenting in the array. Source: https://stackoverflow.com/questions/2889777/difference-between-hashmap-linkedhashmap-and-sortedmap-in-java

 12
Author: Guerra, 2017-05-23 12:37:32

You can use functional operations:

map.forEach((key, value) -> {
   System.out.println("key: " + key + ", value: " + value);
});

Not Working IDEONE .

 9
Author: Renan Gomes, 2020-04-24 18:47:22
    Map<Integer,String> mapa=new HashMap<Integer, String>();
    mapa.put(1, "ze");
    mapa.put(2, "mane");
    Set<Integer> chaves = mapa.keySet();  
    for (Iterator<Integer> it = chaves.iterator(); it.hasNext();){  
        Integer chave = it.next();  
        if(chave != null){  
            System.out.println(chave + mapa.get(chave));  
        }
    }  
 6
Author: NilsonUehara, 2013-12-30 20:02:01

There is also the option to use the Library Guava. Take a look at the API and the wiki of the Maps class.

Has several interesting methods, such as difference to get the difference between 2 maps, transform*, filter *, etc. Depending on what you want to do, use one of these methods to transform, filter, etc. it can generate a simpler and easier to read code.

 3
Author: Thiago Veronese, 2014-01-30 13:33:53