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
Matthew Francis
6,967 PointsNewbie - HashMap, why use entrySet();?
Why do you want to transform it to a set?
For example in
Map<String> test = new HashMap<String>();
for(Map.entry keyandvalue : test.entrySet()){
keyandvalue.getKey();
}
Would work.
But this would not work:
for(Map.entry keyandvalue : test){
keyandvalue.getKey();
}
Why do we need to turn the HashMap into a set in order for the code block to work? Why can't java understand the second block of code?
1 Answer
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsFirst of all take a look how foreach works. In order to do foreach you have to have on the left side Object and on the right side, after : Collection<Object>.
for (Object object: Collection<Object>)
Let's come back to Map. When you type
for (Map.entry entry: test.entrySet())
What you are doing behind the scenes is this:
for (Entry<K,V> entry: Set<Map.Entry<K,V>>)
Which looks totally right: because you are iterating over Collection of Entries. Not let me try to explain my view on Maps:
Map is not a collection, like Set or List that can be iterated in foreach. So in order to use foreach with Map, you have to make Collection of Map entries.
You can ask why Map is not a collection, simply because it is ambiguous how to make Collection from Map. Here take a look at documentation, e.g.:
"The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings."
Taken from: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
That's all I can come up with.
Matthew Francis
6,967 PointsMatthew Francis
6,967 PointsMy fault for not checking the docs thorughly!
This is the exact answer I'm looking for, thanks again!