Java Iterate through a HashMap Example

This examples shows you how to iterate through a HashMap in Java

Iterate over a collection or data set in Java is a very common task. You can use it to print or manipulate the data. Following examples show three different approaches on how to iterate over a HashMap. Depending on your Java version you can choose one of them.

Using for each to iterate through a HashMap

This is the advised approach. It gives you full control over the keys and values in the map. With this approach you actually iterate through the EntrySet of the map and you get the key and value of each entry inside the loop.

For each is available in Java versions 1.5 +

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

public class IterateHashMap {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("key1", "value1");
		map.put("key2", "value2");

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

 

Iterate through HashMap with Lambda Expressions in Java 8

This approach is available in Java 8 + versions.

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

public class IterateHashMap {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("key1", "value1");
		map.put("key2", "value2");

		map.forEach((key,value) -> System.out.println(key + " = " + value));
	}
}




 

Iterate through HashMap using Iterator

This method uses java.util.Iterator to go through the HashMap. This was the default approach in Java 1.4 and older versions. Although the following example uses Generics, so you need Java 1.5 + to execute it

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

public class IterateHashMap {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("key1", "value1");
		map.put("key2", "value2");

		Iterator<Entry<String, String>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> pair = (Map.Entry<String, String>) it.next();
			System.out.println(pair.getKey() + " = " + pair.getValue());
		}
	}
}

 

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Digg thisPin on PinterestShare on RedditShare on StumbleUponPrint this pageEmail this to someone

Leave a Reply

Be the First to Comment!

avatar
wpDiscuz