If somebody could please have a look and help me understand why this is still not working. Very much appreciated.
package com.codegym.task.task08.task0817;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
/*
We don't need repeats
*/
public class Solution {
public static HashMap<String, String> createMap() {
//write your code here
HashMap<String, String> map = new HashMap<>();
map.put("LastName1", "Name1");//create a HashMap with 10 key-value pairs (lastName , name)
map.put("LastName2", "Name1");//changed the first letter to capitals
map.put("LastName3", "Name5");//changed the name of the HashMap from names to map
map.put("LastName4", "Name7");//still not working why?
map.put("LastName5", "Name9");// keys CANNOT be the same
map.put("LastName6", "Name10");//values can be the same but NOT the keys
map.put("LastName7", "Name11");
map.put("LastName8", "Name13");
map.put("LastName9", "Name14");
map.put("LastName10", "Name15");
return map;
}
/* public static int getSameFirstNameCount(HashMap<String, String> map, String name) {
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();//create an iterator
int count = 0;//create and intialize the int count
while(iterator.hasNext())//loops over all the strings checks if there is a next
{
Map.Entry<String, String> pair = iterator.next();// get the next
if(pair.getValue().equals(name)){// compares the values in the pair key-value (lastName, name) with name
count++;// if there are values(name) that are the same +1
}
}
System.out.println(count);
return count;// gives the total number of people with the same name
}*/
public static void removeFirstNameDuplicates(HashMap<String, String> map, String name) {// added String name as second parametershould this not be HashMap instead of Map?
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();//create an iterator
//for(Map.Entry<String, String> entry: map.entrySet())//loop over all the pairs in map
{
while(iterator.hasNext())// loops over the pairs and checks if there is a next pair in the Map
{
Map.Entry<String, String> pair = iterator.next();//gives next pair
//String key = pair.getKey();// to find a particular key but why would I do this?
//String value = pair.getValue(); //get the value of this pair this is now working even after removing (key)
//how to get a value in order ro compare it with another value and to see if they are the same
if(pair.getValue().equals(name)){//to compare the value with name
removeItemFromMapByValue(map, name);// this should call the method to remove this element.
}
}
}
}
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) {
}
}