I also tried this. creating a clone and then removing all elements from the original map. then adding non duplicate key value sets. which worked well when i ran it but again, 1. it won't verify and 2. the removeItemFromMapByValue method is not working for me.
I tried debugging with System. out and discovered that my removeItemFromMapByValue is not doing anything. I must be doing something wrong but cannot figure out what.
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> cloneMap = new HashMap<String, String>(map);
map.clear();
for (Map.Entry<String, String> kv : cloneMap.entrySet()) {
if (!map.containsValue(kv.getValue())) {
map.put(kv.getKey(), kv.getValue());
} else {
removeItemFromMapByValue(map, kv.getValue());
}
}
}
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());
}
}