Skip to main content

How to Iterate Over a Map in Java Using a For-Each Loop

 

Working with key-value pairs is a core part of Java programming, and the Map interface is often your best friend when organizing that kind of data. But how do you loop through it efficiently?

In this post, we'll walk through multiple ways to iterate over a Map using a for-each loop—and when you might want to use each approach.


🧩 What Is a Map in Java?

A Map<K, V> in Java is a collection that maps keys to values. It's commonly implemented via HashMap, TreeMap, or LinkedHashMap. Here’s a basic example:

Map<String, String> map = new HashMap<>();
map.put("Name", "Md.");
map.put("Role", "Developer");

Now let’s explore ways to loop through this map.


1️⃣ Using entrySet() – The Most Efficient Way

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

✅ When to use:

  • When you need both keys and values.
  • Most efficient for accessing both in one loop.

2️⃣ Using keySet() – When You Only Need Keys

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

You can also access the value like this:

System.out.println("Value: " + map.get(key));

⚠️ Note:

This is slightly less efficient than entrySet() if you're fetching values inside the loop.


3️⃣ Using values() – When You Only Care About Values

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

Simple and to the point—great when keys don't matter.


4️⃣ Bonus: Java 8 forEach() with Lambda

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

🎯 Why it's great:

  • Concise and readable.
  • Useful for stream-based processing or functional-style Java.

🧠 Wrap-Up

Each way of iterating over a Map has its own use case:

  • Use entrySet() when you need keys and values.
  • Use keySet() if values are optional or used sparingly.
  • Use values() for value-only loops.
  • Use Java 8+ forEach() for clean and functional code.

Want to go deeper? We could explore how to sort maps, stream them, or even filter them by values. Just say the word!


Follow on LinkedIn

Comments

Popular posts from this blog

Keys.RETURN vs Keys.ENTER in Selenium: Are They Really the Same?

When you're automating keyboard interactions with Selenium WebDriver, you're bound to encounter both Keys.RETURN and Keys.ENTER . At a glance, they might seem identical—and in many cases, they behave that way too. But under the hood, there’s a subtle, nerdy distinction that can make all the difference when fine-tuning your test scripts. In this post, we’ll break down these two key constants, when to use which, and why understanding the difference (even if minor) might give you an edge in crafting more accurate and resilient automation. 🎹 The Subtle Difference On a standard physical keyboard, there are typically two keys that look like Enter: Enter key on the numeric keypad. Return key on the main keyboard (near the letters). Historically: Keys.RETURN refers to the Return key . Keys.ENTER refers to the Enter key . That’s right—the distinction comes from old-school typewriters and legacy keyboard design. Return meant returning the carriage to the beginning ...

Understanding Mistakes in Software Development: Errors, Defects, and Bugs

  Every software team uses the words “error,” “defect,” and “bug,” often interchangeably. But there’s real power in knowing exactly what each term means—and when it applies   1. Mistakes by Phase Phase What You Find What It’s Called Requirements & Design A mistake in the design or plan that doesn’t meet what stakeholders want. Defect Coding A coding or logic mistake in source code Error Testing & Execution An observable malfunction occurring during software execution or testing. Bug  🐞 1.1 Defect A defect is any flaw or mismatch in your requirements or design artifacts. It exists before any code runs. Example: You document “Users must enter a 4-digit PIN,” but stakeholders actually needed 6 digits. That spec mismatch is a defect . 1.2 Error An error is a mistake made while coding —a typo, wrong opera...

Performance Testing, Load Testing, Stress Testing, Volume Testing

  🚀 Performance Testing Performance Testing is a type of non-functional testing that evaluates the speed, stability, scalability, and responsiveness of a software application under a specific workload. 🔹 Goals: Identify bottlenecks Ensure the system meets performance benchmarks Validate response time, throughput, and resource usage Example: Testing how fast a banking app processes 10,000 concurrent transactions. 👥 Load Testing Load Testing is a subset of performance testing that checks how a system behaves under expected or peak user loads . It simulates multiple users accessing the system simultaneously. 🔹 Purpose: Validate system performance under normal and high traffic Identify scalability limits and response delays Example: Simulating 5,000 users shopping during a flash sale on an e-commerce site. 💥 Stress Testing Stress Testing evaluates the system’s robustness and stability by pushing it...