Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures Exploring the Java Collection Framework Maps

Pedro Silva
Pedro Silva
5,363 Points

From where does this Map.Entry comes from?

I got a little curious about Map.Entry that Craig uses in the for each loop in repl and went to look in the documentation, i found the page for Map.Entry but i didn't get where it came from e where can it be used, can anyone shed some light in my curiosity?

Thanks!

1 Answer

Yanuar Prakoso
Yanuar Prakoso
15,196 Points

Hi Pedro

I believe you already visit Map.Entry Java doc and you see that Interface Map.Entry<K,V> has enclosing interface Map. So Map.Entry() is basically a class inside a class (or in this case interface) Map. I know this knowledge is scary to hear for the first time but please just accept it as what it is right now. In future course in Java you will learn more about it. So, when you declare a Map for instance in the form of HashMap it has this interclass Map.Entry built in. What it is for? Well you can see it in the example that Craig gave in the Java repl.

Craig wants to iterate all Keys and its Value corresponding to the Key. Therefore in the HashMap acronym he uses the method entrySet() which you can find out more about it in the related HashMap java doc.

The thing is as explained in the Java doc it returns a Set<Map.Entry<K,V>> thus as you may already understand by now it returns a Set of Map.Entry objects. Therefore to access it and iterate (using for loops) you need to utilize an object instantiated (let's just say created from since we are just mere muggles) from Map.Entry class object in that example the object is entry inside the for (Map.Entry entry : acronyms.entrySet()).

Thus when you already declare entry as Map.Entry object containing a Set of acronyms.entrySet() now you can utilize the feature of Map.Entry which one of them collection view of the elements (the keys and their's corresponding value) inside a map (in this case acronyms). Then you can iterate them just like what Craig did.

I hope this can help a little. Please be advise I am also still learning. Forgive me if some explanation is hard to swallow. Best of luck and keep on coding.

Pedro Silva
Pedro Silva
5,363 Points

Thank you very much Yanuar, really helped!