Iterating through a HashMap in Java

This question already has an answer here:

  • How to efficiently iterate over each entry in a 'Map'? 38 answers

  • From your code we can see the you are using countyData.get("pop") - ie you have hardcoded the key , so it will always return one and the same thing - the value associated with this key .

    PS: You can iterate over all the elements of the map, by using the keys form the keySet :

    Set<KeyClass> keySet = myMap.keySet();
    for(KeyClass key : keySet){
         ValueClass value = myMap.get(key);
         //do stuff
     }
    

    Also you should note that the putAll method will overwrite entries with the same key:

    Copies all of the mappings from the specified map to this map (optional operation). The effect of this call is equivalent to that of calling put(k, v) on this map once for each mapping from key k to value v in the specified map


     for (Map.Entry<String, Integer> countyMarkers: map.entrySet())
        {
            System.out.println(countyMarkers.getKey() + " " + countyMarkers.getValue());
        }
    

    在这里我使用了entrySet()方法,它返回包含在此映射中的映射的Set视图,然后通过这些映射可以使用getKey()和getValue()方法获取键和值


    The problem is:

    String pop = countyData.get("pop").toString();
    

    you hard code the key to get "pop"

    you probably want:

     String pop = countyData.get(county).toString();
    
    链接地址: http://www.djcxy.com/p/23978.html

    上一篇: 使用FlurryAgent.onEvent(String eventId,Map <String,String>参数)

    下一篇: 在Java中迭代HashMap