I have a program that adds the name of the donors as key in the HashMap with their Cities(ArrayList of city) as value. So, I have to take the name of the donor and first check whether this name is available in the map or not , if the name is available and the donor is donating from a different city then I need to update the cities arraylist in the map and if it is a new donor then I need to just add the donor in the map.
if anyone can help me with this problem, I have been facing great crisis because of this. Totally stucked.
I have attached my code.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.HashMap;
public class MultCityMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
CollectionUtil cu = new CollectionUtil();
String donorName,city;
Scanner sc = new Scanner(System.in);
ArrayList<String> donorCity = new ArrayList<String>();
boolean choiceFlag = true;
while(choiceFlag){
System.out.println("Enter name");
donorName = sc.nextLine();
System.out.println("Enter city name");
city = sc.nextLine();
ArrayList<String> newCity = cu.nameKeyChecker(donorName,donorCity);
newCity.add(city);
cu.addDonor(donorName, newCity);
System.out.println("donate again? (1/0)");
int choice = sc.nextInt(); sc.nextLine();
if(choice == 1)
choiceFlag = true;
else
choiceFlag = false;
}
System.out.println(CollectionUtil.donorMap);
}
}
import java.util.ArrayList;
import java.util.HashMap;
public class CollectionUtil {
static HashMap<String, ArrayList<String>> donorMap = new HashMap<>();
public ArrayList<String> nameKeyChecker(String name, ArrayList<String> city){
if(donorMap.containsKey(name))
return (ArrayList<String>)donorMap.get(name);
else
donorMap.put(name, city);
return (ArrayList<String>)donorMap.get(name);
}
public void addDonor(String name, ArrayList<String> city){
donorMap.put(name, city);
}
}
Map<String, List<String>>instread ofHashMap<String, ArrayList<String>>etc. Also note that sinceget()will already return a value type as defined by the generics (in your caseArrayList<String>) those casts like in(ArrayList<String>)donorMap.get(name)aren't necessary.cu.nameKeyChecker(donorName,donorCity)- here you're reusing the same list for every donor so in the end they'll all share the same list of cities. Instead either replacedonorCitywithnew ArrayList<>()in that call - or better create a new list innameKeyChecker(...)when you need to put one and the list that's passed in isnull.