Sunday, 12 May 2013

How to iterate over a Map in Java?

Just to revise basic of Map go through it demo code. We will use the same piece of code and iterate over it.Purpose of this post is to demonstrate how can we iterate over a Map. We know Map interface does not implement Collection interface and hence we cannot just say someMap.iterator() . To revise Iterators refer to the post on understanding Iterators.Lets see then how do we iterate over a Map.

Java Code : 

package testCodes;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapDemo {

    public static void main(String args[]) {
        Map<String, String> persononalData = new HashMap<String, String>();
        // Populating Map with data
        persononalData.put("Name", "John");
        persononalData.put("Country", "USA");
        persononalData.put("Gender", "Male");
        persononalData.put("Age", "18");
        Iterator<Map.Entry<String, String>> mapIterator = persononalData
                .entrySet().iterator();
        while (mapIterator.hasNext()) {
            Map.Entry<String, String> keyValuPair = mapIterator.next();
            System.out.println("Key is " + keyValuPair.getKey());
            System.out.println("Value is " + keyValuPair.getValue());
        }
    }
}

output :


Understanding the code : 

 As Map is not a Collection we cannot use .iterator() function on it. What we do is we create a set of Entry objects and iterate over it. Internally key-value pair are stores in Entry objects in the Map. We then get iterator of this set and iterate over it. Entry object has key and values stores in it and we can extract them using .getKey() and .getValue() methods.

Smarter Way : 

        for (Map.Entry<String, String> keyValuePairs : persononalData
                .entrySet()) {
            System.out.println("Key is " + keyValuePairs.getKey()
                    + "and value is " + keyValuePairs.getValue());
        }

This is a bit smarter way to do the same iteration. Internally it does the same thing i.e use a iterator and iterate over the Entry set.This may look a bit complex for beginners. So method mentioned above is recommended.

 What if I only wish to iterate over keys or just values?

             Yes there is a way to specifically iterate over keys and values in Map. The .keySet()  function will return a set of keys where as .values() function will return Collection of values.Note once you have the Set you can get it's iterator and iterate over it's values.

Iterate over keys : 

        for (String key : persononalData.keySet()) {
            System.out.println("Key is " + key);
        }

Output : 

Key is Name
Key is Age
Key is Gender
Key is Country

Iterate over Values : 

        for (String value : persononalData.values()) {
            System.out.println("Values is " + value);
        }

Output : 

Values is John
Values is 18
Values is Male
Values is USA

Note : Keys in a Map are unique and hence .keySet() will return a set. Two different keys can have same value and hence values can't form a set(Values in a set are unique) and hence what you get from .values() is a Collection.

Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top