I have already completed the task, but I was wondering why when I used iterator it did not iterate over the map and only checked if the first value in the map was repeated, while the for-each checked all values of the map to see if they were repeated and was able to complete the task. Since I completed the task I can't attach my code but I will just paste the iterator part I was talking about. Thank You!
Iterator:
HashMap<String, String> copy1 = new HashMap<String, String>(map);
HashMap<String, String> copy2 = new HashMap<String, String>(map);
Iterator<Map.Entry<String, String>> iterator = copy1.entrySet().iterator();
Iterator<Map.Entry<String, String>> iterator1 = copy2.entrySet().iterator();
String v;
while (iterator.hasNext()) {
v = iterator.next().getValue();
int count = 0;
while (iterator1.hasNext()) {
if (iterator1.next().getValue().equals(v)) count++;
if (count > 1) {
removeItemFromMapByValue(map, v);
}
}
}
Why did iterator not work but for-each did?
Resolved
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
27 December 2018, 20:14
You never reset the values in iterator1. if you step through the code:
the foreach loop like this
+2
Guadalupe Gagnon
27 December 2018, 20:16
You would have to make your iterator look like this:
0
Will Rosenberg
27 December 2018, 20:41
Ok. This makes a lot of sense thank you.
0