I came across the following code :
for(Map.Entry<Integer,VmAllocation> entry : allMap.entrySet()) {
// ...
}
What does Map.Entry<K,V> mean ? What is the entry object ?
I read that the method entrySet returns a set view of the map. But I do not understand this initialization in for-each loop.
Map.Entry is a key/value pair that forms one element of a Map. See the docs for more details.
You typically would use this with:
Map<A, B> map = . . .;
for (Map.Entry<A, B> entry : map.entrySet()) {
A key = entry.getKey();
B value = entry.getValue();
}
If you need to process each key/value pair, this is more efficient than iterating over the key set and calling get(key) to get each value.
Go to the docs: Map.Entry
Map.Entry is an object that represents one entry in a map. (A standard map has 1 value for every 1 key.) So, this code will iterator over all key-value pairs.
You might print them out:
for(Map.Entry<Integer,VmAllocation> entry : allMap.entrySet()) {
System.out.print("Key: " + entry.getKey());
System.out.println(" / Value: " + entry.getValue());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With