My thought is, as the method removeItemFromMapByValue will delete all the elements which contain the parameter "name" in the original map including the element we are iterating currently, calling removeItemFromMapByValue directly will cause fault by deleting all elements. Thus we need to exclude the current element in the original map and check if there are any elements have the same value as the current one. We could do this by creating a duplicated map. If there are, we call the method removeItemFromMapByValue to remove them all, if not, we continue to iterate the next element without delete the last element itself.
Is all above right? If so, is there anything wrong with my code? Any idea will be appreciated!
package zh.codegym.task.task08.task0817;
import java.util.*;
/*
我们不需要重复的内容
*/
public class Solution {
public static HashMap<String, String> createMap() {
//在此编写你的代码
HashMap<String, String> map = new HashMap<String, String>();
map.put("Rose", "Derrick");
map.put("James", "Derrick");
map.put("Durant", "Kevin");
map.put("Curry", "Stephen");
map.put("Irving", "Kyrie");
map.put("Tompson", "Klye");
map.put("Johnson", "Joe");
map.put("Young", "Nick");
map.put("Lee", "David");
map.put("Wall", "John");
return map;
}
public static void removeFirstNameDuplicates(Map<String, String> map) {
//在此编写你的代码
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()){
//String name = it.next().getValue();
//String lastName = it.next().getKey();
Map.Entry<String, String> pair = it.next();
String name = pair.getValue();
String lastName = pair.getKey();
HashMap<String, String> copy = new HashMap<String, String>(map);
copy.remove(lastName);
//for(Map.Entry<String, String> pair2 : copy.entrySet()){
if(copy.containsValue(name)){
removeItemFromMapByValue(map, name);
//break;
// }else
// continue;
}
}
}
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 removeOneValue(HashMap<String, String> map, String value){
Collection<String> col = map.values();
col.remove(value);
return map;
}
*/
public static void main(String[] args) {
}
}