0

这是我的代码:

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??
        }
    }
}

我想从以“印度”为键的哈希图中向另一个 ArrayList 添加值?

我试过了..

result.add(CountryMap.get("India"));

但它没有奏效。它添加所有值。

4

3 回答 3

1

解决方案1:

    result.addAll(CountryMap.get("India"));

解决方案2:

    result.add(CountryMap.get("India").toString());

请尝试查看引发的所有函数和异常。如果有效请回复

于 2012-06-28T12:01:16.730 回答
0
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"
        }
    }
}
于 2012-06-29T06:53:46.940 回答
0

嗨,我知道这已经快一个月大了,但我忍不住想给它一些想法。如果我的问题正确,解决方案非常简单。

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+" ");
        }
}
于 2012-07-29T17:17:51.143 回答