After struggling for 2 days I could not find the solution. But what I got is that we need to use
for (String key : copy.keySet())
I am still not used to enhanced for loop. Can someone please convert the enhanced for loop to longer version of for loop? And, little explanation will also help.
Thank you
Vinay
Level 11
Please help!
Resolved
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Nouser
27 January 2021, 09:35solution
keySet() returns a 'Set view' of the keys in the map. Means you now have a set you can iterate over and do not need to use the entire map. However the wet is still connected to the map. If you modify a set entry, the entry in the map gets modified as well.
Set has no good possibility except an iterator to get an element. So that's what we are doing now. Create an iterator and iteratate over the Set. Lastly we output the keys
When we write that with an enhanced for loop it is much shorter. You can read it like: for each String s in keysOfMap output s.
Of course you won't have to use keySet(). You just could loop over the entire map and get the keys from there. That syntax is a little bit more complex but that is what you already have seen the CG guys use.
In long form that's
entrySet() returns again a set view of the map. Iterating over this set is as described above. You can use an iterator or a for-each loop.
You can write that shorter, if you initilaize the set inside the for-each loop.
+6
Vinay
28 January 2021, 13:40
Thank you Nouser.
0
Maxim Raitin
9 March 2021, 13:29
I tried so hard this (Map.Entry<String, Date> element : mapElements) and in the end this doesn't even matter..
TY man!
0