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

28

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
source

5 answers

37

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

for (Map.Entry<String,Integer> pair : myHashMap.entrySet()) {
    System.out.println(pair.getKey());
    System.out.println(pair.getValue());
}
    
answered by 11.12.2013 в 17:13
11

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
5
    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
4

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
3

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