saplingPro
saplingPro

Reputation: 21329

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

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.

Upvotes: 8

Views: 17303

Answers (4)

Aurand
Aurand

Reputation: 5537

An entry is a key/value pair. In this case, it is a mapping of Integers to VmAllocation objects.

As the javadoc says

A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.

Upvotes: 3

TheKojuEffect
TheKojuEffect

Reputation: 21101

You can learn about Map.Entry Docs

A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.

Check For Each Loop Docs

for(Map.Entry<Integer,VmAllocation> entry : allMap.entrySet()) 

entry is a variable of type Map.Entry which is instantiated with the Entry type data in allMap with each iteration.

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234847

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.

Upvotes: 11

Nicole
Nicole

Reputation: 33207

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());
}

Upvotes: 5

Related Questions