πŸ” Java How-To Examples
Estimated reading: 3 minutes 27 views

πŸ” Java HashMap Loop – Iterate Over Keys, Values, and Entries

🧲 Introduction

HashMap is one of the most used data structures in Java. Whether you’re counting word frequencies, mapping users to settings, or processing key-value data, knowing how to loop through a HashMap efficiently is a must.

By the end of this article, you’ll know how to:

  • βœ… Iterate over keys, values, and key-value pairs
  • βœ… Use both classic and Java 8+ looping styles
  • βœ… Choose the best loop for your use case

πŸ“˜ Sample HashMap

Let’s use this HashMap<String, Integer> for all examples:

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);
map.put("Mango", 15);
map.put("Grapes", 12);

βœ… This map stores fruit names and their quantities.


πŸ” 1. Loop Through Keys (keySet)

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

βœ… Explanation:

  • map.keySet() returns a set of all keys.
  • map.get(key) fetches the corresponding value.

πŸ’‘ Use this if you only need to process keys.


πŸ”„ 2. Loop Through Values (values)

for (Integer value : map.values()) {
    System.out.println("Value: " + value);
}

βœ… Explanation:

  • map.values() returns all values.
  • Doesn’t give access to keys.

πŸ’‘ Use this when keys are not needed.


πŸ”ƒ 3. Loop Through Entries (entrySet)

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

βœ… Explanation:

  • entrySet() provides both key and value in each loop.
  • entry.getKey() and entry.getValue() access the elements.

πŸ’‘ This is the most efficient and preferred method for full map traversal.


πŸš€ 4. Java 8 forEach + Lambda

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

βœ… Explanation:

  • Uses forEach() with a lambda expression.
  • Clean and functional style.

πŸ’‘ Best for modern Java codebases (Java 8+).


πŸ“‹ Comparison Table

Loop TypeAccess KeysAccess ValuesAccess EntriesJava Version
keySet()βœ… Yesβœ… Yes (with get)❌ NoJava 1.2+
values()❌ Noβœ… Yes❌ NoJava 1.2+
entrySet()βœ… Yesβœ… Yesβœ… YesJava 1.2+
forEach() (Lambda)βœ… Yesβœ… Yesβœ… YesJava 8+

πŸ“Œ Summary

In this article, you learned:

  • βœ… Multiple ways to loop through a HashMap in Java
  • βœ… When to use keySet(), values(), entrySet(), and forEach()
  • βœ… Best practices for modifying or filtering data

Knowing the right iteration method boosts performance and keeps your code clean.


❓FAQ – Java HashMap Looping

❓Which loop is the most efficient for HashMap?

βœ… entrySet() loop is generally the fastest and most memory-efficient when both keys and values are needed.

❓Can I modify values during looping?

Yes. Use entry.setValue(newValue) inside an entrySet() loop to modify values directly.

❓Can I remove elements while looping?

Use an Iterator to safely remove elements during iteration:

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    if (entry.getValue() < 15) {
        iterator.remove();
    }
}

Share Now :

Leave a Reply

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

Share

HashMap Loop

Or Copy Link

CONTENTS
Scroll to Top