public class Main{
public static HashMap<String,String> createMap(){
HashMap<String,String> map = new HashMap();
map.put("Иванов", "Иван");
map.put("Пупкин", "Вася");
map.put("Коваленко", "Петя");
map.put("Лубнов", "Иван");
return map;
}
public static void removeTheFirstNameDuplicates(HashMap<String,String>map){
//сюда надо вставить решение
}
public static void removeItemFromMapByValue(HashMap<String,String>map,String value){
HashMap<String,String>copy = new HashMap(map);
for(Map.Entry<String, String> pair: copy.entrySet()){
if(pair.getValue().equals(value)){
map.remove(pair.getKey());
}
}
}
public static void removeTheFirstNameDuplicates(HashMap<String,String>map){
HashMap <String,String> map2 = new HashMap(map);
HashMap <String,String> map3 = new HashMap(map);
for(Map.Entry<String, String> pair : map2.entrySet()){
for(Map.Entry<String, String>pair1 :map3.entrySet()){
if(pair.equals(pair1.getValue())){
removeItemFromMapByValue(map,pair.getValue());
}
}
}
}
public static void removeTheFirstNameDuplicates(HashMap<String,String>map){
HashMap<String, String> copy1 = new HashMap<String, String>(map);
HashMap<String, String> copy2 = new HashMap<String, String>(map);
for (Map.Entry<String, String> pair1: copy1.entrySet())
{
int count = 0;
for (Map.Entry<String, String> pair2: copy2.entrySet()) {
if (pair1.getValue().equals(pair2.getValue())) {
count++;
}
}
if (count > 1) {
removeItemFromMapByValue(map, pair1.getValue());
}
}
}
public class ReplaceFromMapTest {
public static void main(String[] args) {
if(deleteNamesake(getNames())) {
System.out.println("люди с одинаковыми именами были удалены из \"списка\".");
}
}
public static Map<String, String> getNames() {
Map<String, String> names = new HashMap<String, String>();
names.put("Иванов", "Иван");
names.put("Пупкин", "Вася");
names.put("Коваленко", "Петя");
names.put("Лубнов", "Иван");
return names;
}
public static boolean deleteNamesake(Map<String, String> names) {
boolean result = false;
Collection<String> allFirstNames = names.values();
Set<String> delNames = new HashSet<String>();
for(Map.Entry<String, String> p : names.entrySet()) {
if(Collections.frequency(allFirstNames, p.getValue()) > 1) {
delNames.add(p.getKey());
}
}
if(delNames.size() > 0) {
for(String n : delNames) {
names.remove(n);
result = true;
}
}
return result;
}
}