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?
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?
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());
}
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
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));
}
}
You can use functional operations:
map.forEach((key, value) -> {
System.out.println("chave: " + key + ", valor: " + value);
});
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.