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


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

asked by Marconcilio Souza 11.12.2013 в 17:01

5 answers


I like to use FOR loops because the code gets leaner:

for (Map.Entry<String,Integer> pair : myHashMap.entrySet()) {
answered by 11.12.2013 в 17:13

Using the entrySet() method, 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: link

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

The entrySet() does not guarantee the iteration order, whereas the LinkedHashMap<K,V> will iterate exactly in the order it is displaying in the array. Source: link

answered by 11.12.2013 в 17:04
    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));  
answered by 11.12.2013 в 17:10

You can use functional operations:

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

Running on IDEONE .

answered by 20.12.2016 в 12:19

You can also use the Guava library. Take a look at API and in the Wiki of the Maps class.

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

answered by 30.01.2014 в 13:46