Different Ways Of Iterating Map In Java – Including forEach() and stream() Of Java 8

Introduction

Map in Java is an interface. It stores data as key-value pair. We will learn different ways to iterate over Map including Java 8 stream() and forEach().

Basics of Map

The Map is an interface in Java which can be used to store data as key-value pairs. If we want to store details of a person such as First name, last name, address, and age then we can use Map here from Java. First name, last name, address, and age are keys and the person’s details for these keys are values.

Since Map is an interface, we can not instantiate it. We need to use its implemented classes such as HashMap, TreeMap etc. Please note that the Map interface is not part of the Collection interface.

Below is a sample program –

package Maps;

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

public class WaysOfInteratingMap {
	
	public static void main(String[] args) {
		Map personData = new HashMap<>();
		personData.put("FirstName", "Amod");
		personData.put("LastName", "Mahajan");
		personData.put("Address", "New York");
		personData.put("Age", "30");	
		System.out.println(personData);		
	}
}

Output

{Address=New York, FirstName=Amod, LastName=Mahajan, Age=30}

We can print the entire Map data i.e. key-value pair as shown above but in real-time we may be required to iterate the Map to perform different actions. In this post, we will see different ways of iterating over the Map including Java 8 methods.

Iterating using entrySet() method

Map interface provides a method called entrySet() which returns a Set view of the mappings contained in the map. Entry is an inner static interface of Map.

// Iterating using entrySet() method
Set> entries = personData.entrySet();
for(Entry entry : entries)
{
    System.out.println(entry.getKey()+" : "+entry.getValue());
}

Output

Address : New York
FirstName : Amod
LastName : Mahajan
Age : 30

Iterating using keySet() method

The above method gives us key and value mappings but we can also get all keys using the keySet() method and iterate over it. This method returns a Set of all keys in Map.

// Iterating using keySet() method
Set allKeys = personData.keySet();
for(String key : allKeys)
{
    System.out.println(key + " : "+personData.get(key));
}

Output

Address : New York
FirstName : Amod
LastName : Mahajan
Age : 30

Iterating using forEach() method – Java 8

We can directly use the forEach() method of Map introduced in Java 8. With lambda, we can make it shorter.

// Iterating using forEach() method with lambda
personData.forEach((key,value) -> System.out.println(key + " : "+ value));
// Iterating using forEach() method without lambda
personData.forEach(new BiConsumer() {
	@Override
	public void accept(String key, String value) {
        	System.out.println(key + " : "+ value);	
	}
		
});

Output

Address : New York
FirstName : Amod
LastName : Mahajan
Age : 30

Iterating using stream() – Java 8

We can also use the stream() method which may be an indirect way of the above method. This method will be useful if you want to perform some actions on data.

// Iterating using stream() method
personData.keySet().stream().forEach((key) -> System.out.println(key + " : "+ personData.get(key)));
personData.entrySet().stream().forEach((keyValuePair) -> System.out.println(keyValuePair.getKey()+" : "+keyValuePair.getValue()));
 

Output

Address : New York
FirstName : Amod
LastName : Mahajan
Age : 30

Complete Program

package Maps;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;

public class WaysOfInteratingMap {
	
	public static void main(String[] args) {
		Map personData = new HashMap<>();
		personData.put("FirstName", "Amod");
		personData.put("LastName", "Mahajan");
		personData.put("Address", "New York");
		personData.put("Age", "30");	
		System.out.println(personData);	
		
		// Iterating using entrySet() method
		Set> entries = personData.entrySet();
		for(Entry entry : entries)
		{
			System.out.println(entry.getKey()+" : "+entry.getValue());
		}
		System.out.println("========================================");
		// Iterating using keySet() method
		Set allKeys = personData.keySet();
		for(String key : allKeys)
		{
			System.out.println(key + " : "+personData.get(key));
		}
		System.out.println("========================================");
		// Iterating using forEach() method with lambda
		personData.forEach((key,value) -> System.out.println(key + " : "+ value));
		// Iterating using forEach() method without lambda
		personData.forEach(new BiConsumer() {
			@Override
			public void accept(String key, String value) {
				System.out.println(key + " : "+ value);	
			}
			
		});
		// Iterating using stream() method
		personData.keySet().stream().forEach((key) -> System.out.println(key + " : "+ personData.get(key)));
		System.out.println("========================================");
		personData.entrySet().stream().forEach((keyValuePair) -> System.out.println(keyValuePair.getKey()+" : "+keyValuePair.getValue()));
	}
}

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe to my YouTube channel.
#ThanksForReading
#HappyLearning

Leave a Reply

Your email address will not be published. Required fields are marked *