How to Iterate a Map in Java

Last updated by Swaminathan Iyer on Mar 29, 2026 at 11:16 PM

Article written by Shashi Kadapa, under the guidance of Neeraj Jhawar, a Senior Software Development Manager and Engineering Leader. Reviewed by Manish Chawla, a problem-solver, ML enthusiast, and an Engineering Leader with 20+ years of experience.

| Reading Time: 3 minutes

Java iterate map is a method of parsing through all key-value pairs in a database or page so that they can be modified and processed. Iterating a map in Java is done to access and display controls, apply conditional logic and checks, update entries, for data analysis and transformation, and for data integrity and debugging.

Important functions to iterate over a map in Java are entrySet(), keySet(), and values(), and these are used for iteration and retrieving data. The blog examines nine methods to iterate over maps in Java. Along with code snippets and use cases, the blog also compares important parameters and when they are used.

The blog gives code snippets for several functions and use cases, and important links to resources. To master iterating maps in Java, practice coding in a Java IDE, read articles and blogs on how iteration is used in big data, and analyze the code structure.

Key Takeaways

  • Iterating a map in Java means accessing and processing key-value pairs using methods like entrySet(), keySet(), and values().
  • entrySet() is the most efficient and preferred method when both keys and values are needed, as it avoids extra lookups.
  • keySet() and values() are useful when you only need keys or values, but keySet() can be less efficient due to additional get() calls.
  • Methods like Iterator and forEach() offer flexibility, with Iterator enabling safe modifications and forEach() providing concise, readable code.
  • Choosing the right iteration method depends on the use case, performance needs, and whether you need to read, modify, or process map data.

What Is a Map in Java?

In Java, a map is a data structure where data is stored in key-value pairs, with each key mapping to only one value. A map is used for caching to store results by an input key, for frequency counting, lookup tables, in config settings, and grouping data.

entrySet(), keySet(), and values() in Java maps help in iteration and retrieving data in a map. They return a collection view along with the original map so that changes in the view are seen in the map.

entrySet() returns a set view of key-value mappings. An element in the returned set is an object of type Map.Entry<K, V>, that represents a one key/ value pair. Use case is the optimized method that does not take extra lookups using get() and iterate over the key pair. Access for a key and value is done by using the getKey() and getValue() methods on the Map.Entry objects.

keySet() provides a set view of all the map keys. It has only the keys from the map and is used to process through the keys. When a value is needed, the get(key) method on the original map for each key is used. It is less efficient than entrySet().

values() provide a collection view of all values in the map. It only has value from the map and may carry duplicate values. Contains only the values from the map. The collection may contain duplicate values, as the map only enforces unique keys. It is used to work with values, calculate sums, and check if a specific value exists.

The following table gives features comparison of map, list, and set.

Feature Map List Set
What it stores Key-value pairs Ordered elements Unique elements
Duplicates Keys: No, Values: Yes Yes No
Null values Depends on impl. Yes (multiple) One null (most impls)
Order Depends on impl. Insertion order maintained Depends on impl.
Index access By key By index (get(0)) Not supported
Main interface Map<K,V> List<E> Set<E>
Extends Collection No Yes Yes
Common implementations HashMap, TreeMap, LinkedHashMap ArrayList, LinkedList HashSet, TreeSet, LinkedHashSet
Lookup speed O(1) by key (HashMap) O(n) linear search O(1) (HashSet)
Insertion speed O(1) (HashMap) O(1) amortized (ArrayList) O(1) (HashSet)
Sorted option TreeMap Manual / Collections.sort() TreeSet
Iteration entrySet(), keySet(), values() Enhanced for / iterator Enhanced for / iterator
Best used for Key-based lookup, dictionaries Ordered data, index access Uniqueness checks, deduplication
Example use case Word frequency count Shopping cart items Unique usernames

Further Reading: Sorting a HashMap

How to Iterate Through a Map in Java

Iteration cannot be done directly over a map, but over key-value pairs, keys, or values. Some methods are using entrySet(), keySet(), values(), forEach(), Iterator, and others. Let us look at these methods.

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

Map.entrySet() is used in iteration to get the key and values, and gives direct access without extra lookups.

A code snippet explains how to iterate a map in Java to map the student names – keys and score – values, of three students, is given below. The Map.entrySet() returns a set of Map.Entry<K, V> objects, each holding a key-value pair.

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

Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String  key   = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " -> " + value);
}

// Output (order may vary with HashMap):
// Alice   -> 30
// Bob     -> 25
// Charlie -> 35
💡 Tip Callout: ‘entrySet() is the recommended default for most cases, it avoids the extra hash lookup that keySet() + get() requires.’

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

Iterating Over Keys using keySet() and values() method is done when only keys in the map need to be accessed. values() is used only when values are required.

The following code iterates the keys for three students.


Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);

for (String key : map.keySet()) {
    System.out.println("Key: " + key);
}

// Output (order may vary):
// Key: Alice
// Key: Bob
// Key: Charlie

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

The iterator Over Map.Entry<K, V> method is used to safely remove entries from the map during iteration. The following code snippet shows three entries removed from the map.

Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

// Output (order may vary):
// Alice   -> 30
// Bob     -> 25
// Charlie -> 35
⚠️ Warning Callout: ‘ConcurrentModificationException: if you modify a Map during a for-each loop, it throws this exception. Use Iterator.remove() instead.’

Method 4: Using the forEach(action) Method

The forEach(action) Method is a shorter method to loop and is used to carry out specific actions on the collection elements.

Code snippet shows the basic syntax and output.


Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);

map.forEach((key, value) -> {
    System.out.println(key + " -> " + value);
});

// Output (order may vary):
// Alice   -> 30
// Bob     -> 25
// Charlie -> 35

Inline Lambda, single statement is used when the body is a single expression, braces and semicolons can be dropped. The code is: map.forEach((key, value) -> System.out.println(key + ” -> ” + value));

Method 5: Iterating Over Keys and Searching for Values

The iterating over keys and searching for values method is used to locate entries that match a condition using a key pattern, value criterion, or both. It loops through keys first, then calls get(key) for each, and this is an additional lookup.

Code snippet for basic key iteration with value lookup is:


Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);
map.put("Anna", 28);

// Search for keys starting with "A"
for (String key : map.keySet()) {
    if (key.startsWith("A")) {
        System.out.println(key + " -> " + map.get(key));
    }
}

// Output:
// Alice -> 30
// Anna  -> 28

Method 6: Iterating a Map Using Spliterator

Iterating a Map Using Spliterator provides parallel and sequential traversal of elements. It splits a data source into parts for concurrent processing and is used for processing large maps and parallel tasks.

Code for obtaining a Spliterator from a map:


Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);
map.put("Anna", 28);

// Obtain Spliterator from entrySet
Spliterator<Map.Entry<String, Integer>> spliterator = map.entrySet().spliterator();

A Spliterator can also be obtained from keySet().spliterator() or values().spliterator().

Method 7: Iterating a Hashtable Using Enumeration

Iterating a hashtable using Enumeration is a legacy method appearing in legacy code bases designed specifically for use with classes like Vector and Hashtable.

Following code is used to obtain an enumeration from hashtable:


// Obtaining an Enumeration from Hashtable
// Hashtable provides three methods that return an Enumeration:

Hashtable<String, Integer> table = new Hashtable<>();
table.put("Alice",   30);
table.put("Bob",     25);
table.put("Charlie", 35);
table.put("Anna",    28);

Enumeration<String>  keys   = table.keys();      // keys only
Enumeration<Integer> values = table.elements(); // values only
💡 Pro Tip: ‘Hashtable does not have a direct entrySet() based Enumeration, use keys() with get() or convert to modern iteration for entry-pair access.

Method 8: Iterating a Map After Converting It to an Array

Iterating a map after converting to an array helps to use ordered indexing, sorting algorithms, and functional methods (like map, filter, reduce). These are not directly available on the Map structures. It is used for sorting by value, to obtain easier access for index-based iteration and functional methods, for simplified data manipulation, and for rendering and exporting.

Following code is used to convert keys to an array:


Map<String, Integer> map = new HashMap<>();
map.put("Alice",   30);
map.put("Bob",     25);
map.put("Charlie", 35);
map.put("Anna",    28);

// Convert keys to String array
String[] keysArray = map.keySet().toArray(new String[0]);
for (String key : keysArray) {
    System.out.println("Key: " + key);
}

// Output (order may vary):
// Key: Alice
// Key: Bob
// Key: Charlie
// Key: Anna

Method 9: Iterating and Updating Values Using replaceAll()

Iterating and Updating Values Using replaceAll() method replaces all values in place.

The following code shows 10 added to the initial values.


Map<String, Integer> map = new HashMap<>();
map.put("Alice",   30);
map.put("Bob",     25);
map.put("Charlie", 35);
map.put("Anna",    28);

// Increment every value by 10
map.replaceAll((key, value) -> value + 10);
System.out.println(map);

// {Alice=40, Bob=35, Charlie=45, Anna=38}

Which Method Should You Use? (Quick Comparison)

The following table compares the 9 iteration methods giving the method, when to use, key and value access, Java version, and the performance.

Method When to use Key + value access Java version Performance
entrySet()
for-each
General-purpose iteration needing both key and value  Both,  single lookup Java 1.2 Fast
keySet()
for-each
Iterating or filtering keys only; value lookup optional  Key only
Value needs get()
Java 1.2 Medium
values()
for-each
Aggregating, summing, or filtering values only  Value only
No key access
Java 1.2 Fast
Iterator
Map.Entry<K,V>
Safe removal or complex conditional mutation during traversal  Both via entry Java 1.2 Fast
forEach()
BiConsumer
Clean read-only or side-effect operations; functional style  Both as lambda params Java 8 Fast
keySet()
+ value search
Searching map by key pattern, then looking up matching values  Key only
Value via get()
Java 1.2 Medium
Spliterator
tryAdvance / forEachRemaining
Parallel processing of large maps; size estimation; pipeline integration  Both via Map.Entry Java 8 Fastest (parallel)
Enumeration
Hashtable
Legacy codebases using Hashtable, Vector, or Stack  Key or value
No entry pairs
Java 1.0 Slow (sync)
toArray()
snapshot iteration
Indexed access; sorting independent of map; passing to legacy APIs  Both via Map.Entry[] Java 1.2 Medium
replaceAll()
BiFunction
Transforming all values in-place with a function  Both as BiFunction params Java 8 Fast

Performance Comparison: entrySet() vs keySet() vs forEach()

Performance Comparison table of entrySet() vs keySet() vs forEach():

Aspect  entrySet() (for-each loop) keySet() (with get()) forEach() (Java 8 lambda)
Performance Most efficient for accessing both keys and values, especially in large maps. Least efficient for accessing values because it requires an extra get() lookup per iteration, which adds overhead. Generally good performance, slightly slower than entrySet() due to lambda execution overhead, but fast for modern applications.
Use Case Ideal when you need to work with both the key and the value of each map entry. Only suitable when you need to access only the keys or only the values. Best for concise, readable, read-only code, especially for simple actions on both keys and values.
Readability Straightforward and clear, using a Map.Entry object. Can be more verbose and less intuitive when values are needed. Very concise and functional in style, improving readability for many operations.
Mechanism Iterates directly over a set of key-value pairs (entries). Iterates over a set of keys, requiring a secondary hash lookup (map.get(key)) for each value. Uses internal iteration with a BiConsumer function, handling iteration logic internally.

Interview Questions on Java Map Iteration

Q1. What will happen if you try to store a key that is already present in a Java Map?

If you try to store a key that already exists in a Map, the new value replaces or overwrites the old value associated with that key.

Q2. What is the requirement for an object to be used as a key in a Java HashMap?

The requirement for an object to be used as a key in Java HashMap is that the object must correctly implement hashCode() and equals() to be used as a key in a HashMap. Equal objects must have the same hash code, and equals() must consistently identify duplicates.

Q3. What are the different ways to iterate over Maps in Java?

There are 9 methods to iterate over maps in Java: entrySet() for-each, keySet(), values(), Iterator, forEach(), Streams, Spliterator, Enumeration (legacy), and array conversion.

Q4. Why is entrySet() more efficient than keySet() for iterating a Map?

In Java, entrySet() is more efficient than keySet() for iterating a Map as it accesses both key and value directly in one step. keySet() requires an extra map.get(key) lookup for each entry, adding overhead.

Q5. Can you modify a Map while iterating over it?

You cannot safely modify a Map while iterating with a normal loop, it will throw a ConcurrentModificationException. Use Iterator.remove() for safe removal, or ConcurrentHashMap for concurrent access.

Also Read: How Long Does It Take to Prepare for Coding Interviews?

Conclusion

This blog examined several important topics on the process of iterating a map in Java. The function of iterating a map in Java is used to access and display controls, apply conditional logic and checks, update entries, for data analysis and transformation, and for data integrity and debugging.

Important core functions such as entrySet(), keySet(), and values() were compared, and their use cases examined. entrySet() and Iterator are the most commonly used. Nine methods used to iterate over a map in Java were examined and compared, along with code snippets and use cases.

Each method of iterating over a map in Java is used under specific conditions and for a specific use. These methods are critical while iterating over a database with millions of values and key pairs.

To learn how to iterate a map in Java and master the iteration process, take up coding in a Java IDE, practice, review code examples, read blogs, articles, and other sources

FAQs: Java Iterate Map

Q1. In Java, why is the Collection interface not extended by the Map interface?

In Java, the collection interface is not extended by the map interface since the map represents a different data structure than the collection. Map stores key-value pairs, not single elements, and the structure does not fit the collection contract.

Q2. What is the difference between Iterator and Enumeration in Java?

The difference between iterator and enumeration in Java is that iterator reads and removes elements with the remove() command, while enumeration is a legacy function and does not remove elements.

Q3. What is the advantage of using forEach() introduced in Java 8?

The advantage of using forEach() introduced in Java 8 is that it gives a clean and short method to iterate with lambda expressions. It reduces boilerplate template code to loops and supports functional-style programming.

Q4. How do you iterate a Map over in Java 8 using Streams?

Iteration of a map in Java 8 using Streams is by using map.entrySet().stream().forEach(entry -> …) as it supports filter, map, and collect operations on entries.

Q5. What is the difference between HashMap and Hashtable iteration?

The difference between HashMap and Hashtable iteration is that HashMap uses Iterator (fail-fast). Hashtable uses Enumeration (legacy) or Iterator. Hashtable is synchronized, HashMap is not.

References

  1. Iterate Over a Map in Java

Recommended Reads:

Last updated on: March 29, 2026
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

Learn to build AI agents to automate your repetitive workflows

Upskill yourself with AI and Machine learning skills

Prepare for the toughest interviews with FAANG+ mentorship

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

Transform Your Tech Career with AI Excellence

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

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

Webinar Slot Blocked

Loading_icon
Loading...
*Invalid Phone Number
By sharing your contact details, you agree to our privacy policy.
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

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

Registration completed!

See you there!

Webinar on Friday, 18th April | 6 PM
Webinar details have been sent to your email
Mornings, 8-10 AM
Our Program Advisor will call you at this time