Iterating a HashMap

Here is a quick example that shows how to iterate over a HashMap.

You have the option of using the map key set or the map entry set.

 

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashDemo {

	public static void main(String[] args) {

		Map<String, String> theMap = new HashMap<String, String>();

		theMap.put("alfa", "john");
		theMap.put("beta", "mary");
		theMap.put("code", "susan");

		// iterate using keys
		System.out.println("Using Key set");

		Set<String> theKeys = theMap.keySet();
		for (String tempKey : theKeys) {
			String tempValue = theMap.get(tempKey);

			System.out.println("key: " + tempKey + ", value: " + tempValue);
		}

		// iterator using Map.Entry
		System.out.println("\nUsing Map.Entry");

		Set<Map.Entry<String, String>> theMapEntries = theMap.entrySet();
		for (Map.Entry<String, String> tempEntry : theMapEntries) {
			System.out.println("key: "  + tempEntry.getKey() + ", value: "  + tempEntry.getValue());
		}
	}
}

Did you like my blog post?

Signup now and receive an email when I publish new luv2code content.

I agree to have my personal information transfered to AWeber ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

Leave a Reply