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.
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.
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
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.
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
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
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
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));
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
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().
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
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
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}
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 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. |
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.
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.
There are 9 methods to iterate over maps in Java: entrySet() for-each, keySet(), values(), Iterator, forEach(), Streams, Spliterator, Enumeration (legacy), and array conversion.
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.
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?
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
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.
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.
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.
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.
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.
Recommended Reads:
Time Zone:
100% Free — No credit card needed.
Time Zone:
Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.
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.
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
Time Zone:
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
Register for our webinar
Learn about hiring processes, interview strategies. Find the best course for you.
ⓘ Used to send reminder for webinar
Time Zone: Asia/Kolkata
Time Zone: Asia/Kolkata
Hands-on AI/ML learning + interview prep to help you win
Explore your personalized path to AI/ML/Gen AI success
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
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
Time Zone: Asia/Kolkata
Hands-on AI/ML learning + interview prep to help you win
Time Zone: Asia/Kolkata
Hands-on AI/ML learning + interview prep to help you win
Explore your personalized path to AI/ML/Gen AI success
See you there!