Reputation: 725
Here is my code:
public static HashMap<String, ArrayList<String>> CountryMap = new HashMap<String, ArrayList<String>>();
ArrayList<String> stateInd = new ArrayList<String>();
ArrayList<String> stateUSA = new ArrayList<String>();
stateInd.add("GJ");
stateInd.add("MP");
stateUSA.add("NJ");
stateUSA.add("NY");
CountryMap.put("India",stateInd);
CountryMap.put("USA",stateUSA);
for(int i=0;i<CountryMap.size();i++){
for (Entry<String, ArrayList<String>> entry : CountryMap.entrySet()) {
if (entry.getKey().equals("India") {
ArrayList<String> result = new ArrayList<String>();
# how to add Value of CountryMap with "India" as a Key to result ArrayList??
}
}
}
I want to add values to another ArrayList from hashmap which have "India" as key ?
I tried..
result.add(CountryMap.get("India"));
But it didn't worked. It add all values.
Upvotes: 0
Views: 229
Reputation: 2597
Hi I know this is almost a month old but couldn't resist to give my thoughts to it. The solution is quite simple if I got your question right.
public static void main(String[] args) {
HashMap<String, ArrayList<String>> CountryMap = new HashMap<String, ArrayList<String>>();
ArrayList<String> stateInd = new ArrayList<String>();
ArrayList<String> stateUSA = new ArrayList<String>();
ArrayList<String> result = new ArrayList<String>();
stateInd.add("GJ");
stateInd.add("MP");
stateUSA.add("NJ");
stateUSA.add("NY");
CountryMap.put("India",stateInd);
CountryMap.put("USA",stateUSA);
for (String key: CountryMap.keySet()){
if (key.equals("India")){
result.add(key);
}
}
for (String country: result){
System.out.print("\n"+country+" ");
}
}
Upvotes: 0
Reputation: 8741
public class NewClass4{
public static HashMap<String, ArrayList<String>> CountryMap = new HashMap<String, ArrayList<String>>();
public static void main(String[] args)
{
ArrayList<String> stateInd = new ArrayList<String>();
ArrayList<String> stateUSA = new ArrayList<String>();
stateInd.add("GJ");
stateInd.add("MP");
stateUSA.add("NJ");
stateUSA.add("NY");
CountryMap.put("India",stateInd);
CountryMap.put("USA",stateUSA);
ArrayList<String> result = new ArrayList<String>();
result=CountryMap.get("India");
if(result!=null){
// means CountryMap contain key "India"
}
}
}
Upvotes: 0
Reputation: 1643
solutions 1:
result.addAll(CountryMap.get("India"));
solutions 2:
result.add(CountryMap.get("India").toString());
Do try to have a look at all functions and exceptions raised. Reply if it works
Upvotes: 1