How to iterate a map

What is HashMap
A java.util.HashMap is a data structure which stores data in key-value pairs. It implements java.util.Map interface and has methods to retrieve key and values and update values.

Many times you have a map populated with data and you need to want to display its contents or to find an entry with a particular key-value pair. In such situations, iterating(or looping or traversing) over the map becomes necessary. This post will show you different ways to iterate a hashmap in java.

HashMap is an implementation of java.util.Map interface. There are other implementations of this interface. All the methods outlined in this post can be used to iterate over any map.

Method 1: Using entry set
As mentioned earlier, data is stored in a map in key-value pairs also known as entries. These entries are instances of type java.util.Map.Entry which is a nested interface of java.util.Map interface.
Each entry corresponds to a map element and contains key and value for that element with methods to retrieve them(getKey and getValue) and modify them(setKey and setValue).
Entries stored in a map can be retrieved by calling entrySet method on the map. This set can then be iterated using a for loop as shown below.

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
 
public class MapIterator {
   public static void main(String[] args) {
      // create a hashmap
      Map<Integer, String> map = new HashMap<Integer, String>();
      // add values
      map.put(1, "mango");
      map.put(2, "orange");
      map.put(3, "guava");
      // get all map entries
      Set<Entry<Integer,String>> entrySet = map.entrySet();
      // iterate over entries using a for loop
      for (Entry<Integer, String> entry : entrySet) {
         // get key and value of each entry
	 System.out.println("Key: "+entry.getKey());
	 System.out.println("Value: "+entry.getValue());
      }
   }
}

Above code outputs

Key: 1
Value: mango
Key: 2
Value: orange
Key: 3
Value: guava

Method 2: Using iterator on entry set
As discussed above, elements of a map are stored as entries and entrySet method returns those entries in the form of a java.util.Set.
This set can also be iterated using a java.util.iterator. An iterator has a hasNext method which returns true if the set has an element to be iterated and a next method that returns the current element of the set where iterator is positioned.
When next is called, iterator moves on to the next element in the set. Example,

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
public class MapIterator {
   public static void main(String[] args) {
      // create a hashmap
      Map<Integer, String> map = new HashMap<Integer, String>();
      // add values
      map.put(1, "mango");
      map.put(2, "orange");
      map.put(3, "guava");
      // get iterator over the map entries
      Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
      // iterate over entries using a loop
      while(iterator.hasNext()) {
         // get current map entry
	 Entry<Integer, String> entry = iterator.next();
	 // get key and value of each entry
	 System.out.println("Key: "+entry.getKey());
	 System.out.println("Value: "+entry.getValue());
      }
   }
}

Output of above program is

Key: 1
Value: mango
Key: 2
Value: orange
Key: 3
Value: guava

Method 3: Using keySet and iterator
A map has a keySet method which returns a java.util.Set of all the keys of the map. This set of keys can be iterator by using a java.util.iterator.
In every iteration, the iterator’s next method will return the key for a map entry. This key can be used to retrieve the corresponding value using get method of the map. get method accepts a key for the map entry and returns the corresponding value. Example,

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class MapIterator {
   public static void main(String[] args) {
	// create a hashmap
	Map<Integer, String> map = new HashMap<Integer, String>();
	// add values
	map.put(1, "mango");
	map.put(2, "orange");
	map.put(3, "guava");
	// get iterator over the keys of map
	Iterator iterator = map.keySet().iterator();
	// iterate over map key
	while (iterator.hasNext()) {
		// get current map key
		Integer key = iterator.next();
		System.out.println("Key: " + key);
		// get value of this key
		System.out.println("Value: " + map.get(key));
	}
   }
}

Remember that this method will search the entire map for the value of a key till it is found and is thus an inefficient method of iteration when compared to other methods described above.

Similar to keySet method, Map has a values method which returns a collection of values of map.

Method 4: Using forEach method java 8
Starting java 8, forEach method is added to java.util.Map interface. This method can be used to iterate through a hashmap.
In every iteration, it is supplied with two arguments, one is a key and another is the value of current map entry.
In current example, we just print the key and value of the entry.

import java.util.HashMap;
import java.util.Map;
 
public class MapIterator {
   public static void main(String[] args) {
	// create a hashmap
	Map<Integer, String> map = new HashMap<Integer, String>();
	// add values
	map.put(1, "mango");
	map.put(2, "orange");
	map.put(3, "guava");
	map.forEach((key, value) -> {
		// print key
		System.out.println("Key: " + key);
		// print value
		System.out.println("Value: " + value);
	});
   }
}

forEach method takes an argument of type java.util.function.BiConsumer which is a functional interface having a method which accepts two arguments.
Hence, we can supply a Lambda expression to forEach method with two arguments which are the key and value of a map element.

Learn about Lambda expressions, here

If you print both key and value in a single statement, then curly braces in lambda expression can be omitted as shown below.

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

Above code prints

Key: 1, value= mango
Key: 2, value= orange
Key: 3, value= guava

Method 5: Using Stream.of java 8
Java 8 provides static Stream.of method which accepts a collection and returns a stream over it. Retrieve set of map entries using entrySet method which returns a java.util.Set and pass it to Stream.of method.
Now, you can easily iterate over this stream using forEach method as shown below.

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
 
public class MapIterator {
   public static void main(String[] args) {
      // create a hashmap
      Map<Integer, String> map = new HashMap<Integer, String>();
      // add values
      map.put(1, "mango");
      map.put(2, "orange");
      map.put(3, "guava");
      // iterate with Stream.of
      Stream.of(map.entrySet()).forEach(e -> {
         System.out.println(e);
      });
   }
}

This code will print

[1=mango, 2=orange, 3=guava]

If there is any method that is not listed in this post, do mention it here. Keep visiting!!!

0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.