javapythonhashmapequivalent

Loop Java HashMap like Python Dictionary?


In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:

for k,v in d.iteritems():
    print k,v

Is there a way to do this with Java HashMaps?


Solution

  • Yes - for example:

    Map<String, String> map = new HashMap<String, String>();
    // add entries to the map here
    
    for (Map.Entry<String, String> entry : map.entrySet()) {
        String k = entry.getKey();
        String v = entry.getValue();
        System.out.printf("%s %s\n", k, v);
    }