如何使用Hashmap中的键<string,string =“”>?</string,>来检索Value

时间:2012-06-28 11:38:52

标签: java android hashmap

这是我的代码:

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

我想将值添加到hashmap中的另一个ArrayList,其中包含&#34; India&#34;关键?

我试过..

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

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

3 个答案:

答案 0 :(得分:1)

解决方案1:

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

解决方案2:

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

尝试查看引发的所有函数和异常。回复是否有效

答案 1 :(得分: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"
        }
    }
}

答案 2 :(得分: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+" ");
        }
}