I tried creating an empty HashMap called "map2" then adding the unduplicated entry sets to it. then converting that HashMap to the original map. When I run it, it does work as intended however, I cannot seem to get that "removeItemFromMapByValue" method to work. I also tried creating a clone to keep track of the for loop but still not working for me. any input would be greatly appreciated..
package com.codegym.task.task08.task0817;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
/*
We don't need repeats
*/
public class Solution {
public static HashMap<String, String> createMap() {
//write your code here
HashMap<String, String> names = new HashMap<>();
names.put("John", "Doe");
names.put("John1", "Doe1");
names.put("John2", "Doe2");
names.put("John3", "Doe3");
names.put("John4", "Doe4");
names.put("John5", "Doe");
names.put("John6", "Doe1");
names.put("John7", "Doe2");
names.put("John8", "Doe3");
names.put("John9", "Doe4");
return names;
}
public static void removeFirstNameDuplicates(Map<String, String> map) {
//write your code here
HashMap<String, String> map2 = new HashMap<String, String>();
for (Map.Entry<String, String> pair : map.entrySet()) {
if (!map2.containsValue(pair.getValue())) {
map2.put(pair.getKey(), pair.getValue());
} else {
removeItemFromMapByValue(map, pair.getValue());
}
}
map = map2;
System.out.println(map);
System.out.print(map2);
}
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(map.values()))
map.remove(pair.getKey());
}
}
public static void main(String[] args) {
removeFirstNameDuplicates(createMap());
}
}