Make Selenium Easy

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 –

Output

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.

Output

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.

Output

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.

Output

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.

Output

Complete Program

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

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.

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

by Amod Mahajan time to read: 3 min
0
%d bloggers like this: