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