Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Map.Entry<K,V> interface?

Tags:

java

map

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.

like image 746
saplingPro Avatar asked Sep 18 '13 04:09

saplingPro


2 Answers

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.

like image 162
Ted Hopp Avatar answered Sep 26 '22 07:09

Ted Hopp


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());
}
like image 22
Nicole Avatar answered Sep 24 '22 07:09

Nicole