How to Iterate a Map in Java

Last updated by Swaminathan Iyer on Sep 25, 2024 at 11:00 PM
| Reading Time: 3 minutes

If you are preparing for a coding interview, and Java is your programming language of choice, you will benefit from reviewing some of the basics of Java. Software engineers or developers often prefer object-oriented programming languages, like Java, for the features and ease they offer. In this article, we will look at one such feature — the map. Specifically, we’ll cover:

  • What is a Map in Java?
  • How to iterate through a Map in Java: 5 Methods
  • FAQs on how to iterate a Map in Java

What Is a Map in Java?

The Map in Java contains elements based on key-value pairs, i.e., a unique key is assigned to each value. The Map comes in handy when we need to search, update, and remove items based on a key. Following are the types of Maps in Java:

  • HashMap
  • LinkedHashMap
  • Treemap
  • Hashtable

The Map is not a collection, but it is still considered part of the collection. Thus, a Map is an interface that extends the collection interface. An iterator is an interface that is used to iterate through the collection.

How to Iterate Through a Map in Java

In Java, a group of objects that can be represented as a single unit is a collection of objects. We can iterate on collections using iterators. As Maps are not a collection, we cannot iterate on them using iterators.

We have to employ other methods to iterate through a Map. In this article, we will discuss five methods. Let’s get started.

Method 1: Iterating Over Map.entrySet() Using a For-Each Loop

We can use the Map.entrySet() method to return a collection-view(Set<Map.Entry<K, V>>) of the mapping contained in the given Map. Thus, we can easily iterate over the key-value pairs of our Map by using methods of Map.Entry<K, V> like getKey() and getValue().

This method can be used when we need both keys and values in the loop. Here’s the implementation:

 

import java.util.Map;

import java.util.HashMap;

 

public class Method_1

{

public static void main(String[] arg)

{

Map<String,String> myMap = new HashMap<String,String>();

// Inserting entries in map.

myMap.put(“IK”, “InterviewKickstart”);

myMap.put(“Java”, “ProgrammingLanguage”);

myMap.put(“SE”, “SoftwareEngineer”);

// Using for-each loop for iteration over Map.entrySet()

for (Map.Entry<String,String> itr : myMap.entrySet())

System.out.println(“Key = ” + itr.getKey() + “: Value = ” + itr.getValue());

}

}

 

Output:

Key = Java: Value = ProgrammingLanguage
Key = IK: Value = InterviewKickstart
Key = SE: Value = SoftwareEngineer

Method 2: Iterating Over Keys/Values Using keySet() and values() Methods

Method Map.keySet() is used to return a Set view of the keys contained in the Map.

Also, the Map.values() method is used to return the collection-view of the values contained in the Map. We can iterate over keySets or values using for-each loops to get the keys or values of the map separately. This method can be used when we only need to work with keys or values but not both.

Here’s the code:

// Iterating over keys or values using keySet() and values() methods.

 

import java.util.Map;

import java.util.HashMap;

 

public class Method_2

{

public static void main(String[] arg)

{

Map<String,String> myMap = new HashMap<String,String>();

// Inserting entries in map.

myMap.put(“IK”, “InterviewKickstart”);

myMap.put(“Java”, “ProgrammingLanguage”);

myMap.put(“SE”, “SoftwareEngineer”);

// using keySet() for iterating over keys

for (String k : myMap.keySet())

System.out.println(“key: ” + k);

 

// using values() for iterating over values

for (String v : myMap.values())

System.out.println(“value: ” + v);

}

}

 

Output

key: Java
key: IK
key: SE
value: ProgrammingLanguage
value: InterviewKickstart
value: SoftwareEngineer

Method 3: Iterating Using Iterators Over Map.Entry<K, V>

This method is similar to method 1. We used a for-each loop on Map.Entry<K, V> in the first method, but in this method, we use methods like getKey() and getValue() of Map. We can use the entrySet() method to get the Set view of the mapping contained in the map and then can access key or value using getKey() or getValue() method on entry.

Let’s have a look at the code:

 

// Iterating using iterators over Map.Entry<K, V>.

 

import java.util.Map;

import java.util.HashMap;

import java.util.Iterator;

 

public class Method_2

{

public static void main(String[] arg)

{

Map<String,String> myMap = new HashMap<String,String>();

// Inserting entries in map.

myMap.put(“IK”, “InterviewKickstart”);

myMap.put(“Java”, “ProgrammingLanguage”);

myMap.put(“SE”, “SoftwareEngineer”);

// Using iterators

Iterator<Map.Entry<String, String>> it = myMap.entrySet().iterator();

 

// Iterating till the last key value pair.

while(it.hasNext())

{

Map.Entry<String, String> x = it.next();

System.out.println(“Key = ” + x.getKey() + “: Value = ” + x.getValue());

}

}

}

 

Output:

Key = Java: Value = ProgrammingLanguage
Key = IK: Value = InterviewKickstart
Key = SE: Value = SoftwareEngineer

Method 4: Using the forEach(action) Method

In the latest versions of Java, like Java 8, we can iterate a Map using the inbuilt Map.forEach(action) method and lambda expressions in Java.

Here’s the code:

// Using forEach(action) method.

 

import java.util.Map;

import java.util.HashMap;

 

public class Method_2

{

public static void main(String[] arg)

{

Map<String,String> myMap = new HashMap<String,String>();

// Inserting entries in map.

myMap.put(“IK”, “InterviewKickstart”);

myMap.put(“Java”, “ProgrammingLanguage”);

myMap.put(“SE”, “SoftwareEngineer”);

// Using forEach(action) method to iterate over map.

myMap.forEach((key,val) -> System.out.println(“Key = ” + key + “: Value = ” + val));

}

}

 

Output:

Key = Java: Value = ProgrammingLanguage
Key = IK: Value = InterviewKickstart
Key = SE: Value = SoftwareEngineer

Method 5: Iterating Over Keys and Searching for Values

In this method, we first loop over all keys in Map using Map.keySet() method and then search for the value associated with a particular key using Map.get(key) method.

Following is the code to implement this method:

 

// Iterating over keys and searching for values.

 

import java.util.Map;

import java.util.HashMap;

 

public class Method_2

{

public static void main(String[] arg)

{

Map<String,String> myMap = new HashMap<String,String>();

// Inserting entries in map.

myMap.put(“IK”, “InterviewKickstart”);

myMap.put(“Java”, “ProgrammingLanguage”);

myMap.put(“SE”, “SoftwareEngineer”);

// Looping on the keys in the map.

for (String k : myMap.keySet())

{

// Searching for the value.

String val = myMap.get(k);

System.out.println(“Key = ” + k + “: Value = ” + val);

}

}

}

 

Output:

Key = Java: Value = ProgrammingLanguage
Key = IK: Value = InterviewKickstart
Key = SE: Value = SoftwareEngineer

FAANG Interview Questions on Java Iterate Map

Here are some sample questions on iterating through a Map in Java:

  1. What will happen if you try to store a key that is already present in a Java Map?
  2. What is the requirement for an object to be used as a key or value in Java HashMap?
  3. What are the different ways to iterate over Maps in Java?
  4. How do you remove a mapping while iterating over HashMap in Java?

For more tech interview questions and problems, check out the following pages: Interview Questions, Problems, Learn.

FAQs on Java Iterate Map

 

Question 1: In Java, why is the collection interface not extended by the Map interface?

Mainly because they are incompatible, the collection has a method add(Object o). The Map cannot have such a method because it needs a key-value pair. Also, there are other reasons like Map supports keySet, valueSet. Collection classes do not have such methods. Due to such significant differences, the Map interface does not use a collection interface.

 

Question 2: What is the difference between Iterator and Enumeration in Java? 

There are three significant differences between iterators and enumeration:

  • In Enumerator, we can not add/remove elements from a collection, Although, In Iterators, we can remove elements from the underlying collection in the iteration using its inbuilt remove() method.
  • Availability: An Iterator is available in all modern collection classes. An enumerator is available in legacy classes, i.e., Vector/Stack, etc.
  • Iterator has more improved method names than Enumerator. For example, In Enumerator, there is a method hasMoreElement(), which becomes hasNext() in the Iterator.

Recommended Reading

Check out our learn page for more articles on Java:

Ace Your Next Tech Interview With Interview Kickstart!

If you’re looking for guidance and help to nail your next technical interview, sign up for our free webinar.

As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land their dream jobs at Google, Facebook, Apple, Netflix, Amazon, and other Tier-1 tech companies.

Join our webinar to learn more!

———

Article contributed Omkar Deshmukh

 

Last updated on: September 25, 2024
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.

Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.

Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.

Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.

End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.

Select a course based on your goals

Agentic AI

Learn to build AI agents to automate your repetitive workflows

Switch to AI/ML

Upskill yourself with AI and Machine learning skills

Interview Prep

Prepare for the toughest interviews with FAANG+ mentorship

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary