Iterate over Hashmap

HashMap is a popular class of Collections framework which is used to store key value pair. There are 2 ways to iterate over the hashmap and access its keys and values. Let us look at these ways:

Using entrySet() method

entrySet() method returns a Set of Map.Entry<K,V> type, where K is key and V is value. We can iterate over this Set to obtain key and corresponding values let us look at the code:

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

public class Tech4Humans {

	public static void main(String[] args) {
		
		HashMap<Integer,String> map2 = new HashMap<Integer,String>();
		map2.put(10, "This");
		map2.put(20, "Bye");
		map2.put(30, "Say");
		map2.put(40, "Great");
		
		System.out.println("HashMap printing using entrySet():");
		//accessing HashMap using entrySet()
		for(Map.Entry<Integer,String> temp :  map2.entrySet()) 
		{
			System.out.println("Key = "+temp.getKey()+", Value = "+temp.getValue());
		}
		
		
		System.out.println("\nAnother way of writing iteration through entrySet():");
		//another way of writing above iteration
		Set<Entry<Integer,String>> keyValues = map2.entrySet();
		for(Entry<Integer,String> temp : keyValues) 
		{
			System.out.println("Key = "+temp.getKey()+", Value = "+temp.getValue());
		}
	}
}

Output

HashMap printing using entrySet():
Key = 20, Value = Bye
Key = 40, Value = Great
Key = 10, Value = This
Key = 30, Value = Say

Another way of writing iteration through entrySet():
Key = 20, Value = Bye
Key = 40, Value = Great
Key = 10, Value = This
Key = 30, Value = Say

Using keySet() method

keySet() method returns a Set of keys present in the HashMap. We can then iterate over the Set and obtain the keys and corresponding values using get() method of HashMap class.

Let us look at the code:

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

public class Tech4Humans {

	public static void main(String[] args) {
		
		HashMap<Integer,String> map2 = new HashMap<Integer,String>();
		map2.put(10, "This");
		map2.put(20, "Bye");
		map2.put(30, "Say");
		map2.put(40, "Great");
		
		System.out.println("HashMap printing using keySet():");
		//accessing HashMap using keySet()
		Set<Integer> keys = map2.keySet();
		for(Integer keyTemp:keys) 
                {
			System.out.println("Key = "+keyTemp+", Value = "+map2.get(keyTemp));
		}
	}
}

Output

HashMap printing using keySet():
Key = 20, Value = Bye
Key = 40, Value = Great
Key = 10, Value = This
Key = 30, Value = Say

Let us now look at HashMap Iterator.

Leave a Comment