Federer
Federer

Reputation: 34745

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?

Upvotes: 9

Views: 6439

Answers (6)

user25753955
user25753955

Reputation: 1

You can also use one liner using method references as in below example

Map<String, Object> dict=new TreeMap<String, Object>();
    dict.put("age", 20);
    dict.put("height", 1.75);
    dict.put("country", "India");
    dict.put("profession", "developer");
    dict.entrySet().stream().forEach(System.out::println);

Output will be

age=20
country=India
height=1.75
profession=developer

Upvotes: 0

BalusC
BalusC

Reputation: 1108782

As shown in the answers, there are basically two ways to iterate over a Map (let's assume Map<String, String> in those examples).

  1. Iterate over Map#entrySet():

    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    
  2. Iterate over Map#keySet() and then use Map#get() to get the value for every key:

    for (String key : map.keySet()) {
        System.out.println(key + "=" + map.get(key));
    }
    

The second one is maybe more readable, but it has a performance cost of unnecessarily calling get() on every iteration. One may argument that creating the keyset iterator is less expensive because it doesn't need to take values into account. But believe it or not, the keySet().iterator() creates and uses the same iterator as entrySet().iterator(). The only difference is that in case of the keySet() the next() call of the iterator returns it.next().getKey() instead of it.next().

The AbstractMap#keySet()'s javadoc proves this:

The subclass's iterator method returns a "wrapper object" over this map's entrySet() iterator.

The AbstractMap source code also proves this. Here's an extract of keySet() method (somewhere around line 300 in Java 1.6):

public Iterator<K> iterator() {
    return new Iterator<K>() {
        private Iterator<Entry<K,V>> i = entrySet().iterator(); // <-----

        public boolean hasNext() {
            return i.hasNext();
        }

        public K next() {
            return i.next().getKey(); // <-----
        }

        public void remove() {
            i.remove();
        }
    };
}

Note that readability should be preferred over premature optimization, but it's important to have this in mind.

Upvotes: 6

user159088
user159088

Reputation:

The HashMap.entrySet() will return beans of key value pairs similar to the dictionary.iteritems(). You can then loop through them.

I think is the closest thing to the Python version.

Upvotes: 6

bragboy
bragboy

Reputation: 35542

In Java, you can do the same like the following.

    HashMap<String, String> h = new HashMap<String, String>();
    h.put("1","one");
    h.put("2","two");
    h.put("3","three");

    for(String key:h.keySet()){
        System.out.println("Key: "+ key + " Value: " + h.get(key));
    }

Upvotes: 1

Marcelo Lacerda
Marcelo Lacerda

Reputation: 937

Set<Map.Entry> set = d.entrySet();
for(Map.Entry i : set){
  System.out.println(i.getKey().toString() + i.getValue().toString);
}

Something like that...

Upvotes: 3

Richard Fearn
Richard Fearn

Reputation: 25491

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);
}

Upvotes: 21

Related Questions