I tried to debug program and it shows ConcurrentModificationException. I found out that error is in lanes 31-33 cause its tries to iterate and delete items at the same time. So i just wanted to ask why my foreach loop doesnt work? It should be working the same way as if i created iterator the long way, or not? For example:
Iterator<String> iterator = map.values().iterator();
while(iterator.hasNext()){
String nextItem = iterator.next();
if(nextItem == something){
iterator.remove();
}
}
This should be the same as code below?
for(String x : map.values()){
if(x == something){
map.remove(x);
}
}
Is it the same or did i misunderstood this? I read it here that foreach loop is just short way of using iterator.
https://codegym.cc/quests/lectures/questsyntax.level08.lecture02
This is the lane from article:
"Java has shorthand notation for working with iterators. Following the pattern of while and for, one more special statement has been added: for each. It is also indicated using the keyword for."
"The for-each statement is only used for working with collections and containers. It uses an iterator implicitly, but we only see the returned element."
package com.codegym.task.task08.task0817;
import java.util.HashMap;
import java.util.Map;
/*
We don't need repeats
*/
public class Solution {
public static HashMap<String, String> createMap() {
HashMap<String,String> map = new HashMap<>();
map.put("Lname1","Fname1");
map.put("Lname2","Fname2");
map.put("Lname3","Fname3");
map.put("Lname4","Fname1");
map.put("Lname5","Fname4");
map.put("Lname6","Fname5");
map.put("Lname7","Fname6");
map.put("Lname8","Fname2");
map.put("Lname9","Fname2");
map.put("Lname10","Fname9");
return map;
}
public static void removeFirstNameDuplicates(Map<String, String> map) {
for(String value: map.values()){
removeItemFromMapByValue(map,value);
}
}
public static void removeItemFromMapByValue(Map<String, String> map, String value) {
HashMap<String, String> copy = new HashMap<String, String>(map);
for (Map.Entry<String, String> pair : copy.entrySet()) {
if (pair.getValue().equals(value))
map.remove(pair.getKey());
}
}
public static void main(String[] args) {
//HashMap<String,String> map = createMap();
//removeFirstNameDuplicates(map);
}
}