#1
When you're building applications in Java, you'll often need a way to store and quickly look up information using a "key"—just like a dictionary. That’s exactly what a Map in Java helps you do. Whether it’s storing usernames with their passwords, product IDs with product details, or country names with their capitals, Maps are a must-know tool in any Java programmer’s toolkit.
In this article, we’ll walk you through how to use Maps in Java, with simple examples and explanations. We'll cover how to create a Map, add and retrieve values, remove entries, loop through the map, and more.
Let’s dive in!

What Is a Map in Java?

A Map in Java is a collection that stores data in key-value pairs. Each key maps to exactly one value, and keys must be unique. If you try to add a duplicate key, it will simply overwrite the previous value.
Java provides the Map interface and several classes that implement it—like HashMap, TreeMap, and LinkedHashMap. The most commonly used is HashMap, which we’ll focus on in this guide.

Step 1: How to Create a Map

To create a Map in Java, you typically use the HashMap class. Here’s how:
import java.util.HashMap;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) {
        Map<String, String> capitals = new< HashMap<>();
    }
}
In this example:
  • The key type is String (e.g., country name).
  • The value type is also String (e.g., capital city).
  • new HashMap<>() creates the map.

Step 2: Adding Data to a Map

You can add entries using the .put() method:
capitals.put("USA", "Washington, D.C.");
capitals.put("Japan", "Tokyo");
capitals.put("France", "Paris");

If you call .put() on an existing key, it replaces the old value:

capitals.put("France", "Lyon"); // Replaces "Paris" with "Lyon"

Step 3: Retrieving Values from a Map

To get the value for a specific key, use .get(key):
String capital = capitals.get("Japan");
System.out.println("The capital of Japan is: " + capital);

If the key doesn’t exist, .get() will return null.
You can also check if a key exists:

if (capitals.containsKey("Germany")) {
    System.out.println("Found!");
} else {
    System.out.println("Not found!";
}

Step 4: Removing Entries from a Map

You can remove a key-value pair using .remove():
capitals.remove("USA");
You can also remove only if the key matches a specific value:
capitals.remove("France", "Lyon"); // Only removes if value is still "Lyon"

Step 5: Looping Through a Map

Loop through keys:

for (String country : capitals.keySet()) {
    System.out.println("Country: " + country);
}

Loop through values:

for (String city : capitals.values()) {
    System.out.println("Capital: "+ city);
}

Loop through key-value pairs:

for (Map.Entry<String, String> entry : capitals.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
This is the most common way to print everything in a map.

Step 6: Map Size and Other Useful Methods

Here are a few handy methods:
capitals.size();             // Number of entries
capitals.isEmpty();          // True if map is empty
capitals.clear();            // Removes all entries
capitals.containsValue("Paris"); // True if any value is "Paris"

Bonus: Maps with Other Data Types

You’re not limited to String. You can use any object type for keys or values.
Example:
Map<Integer, String> idToName = new HashMap<>();
idToName.put(101, "Alice");
idToName.put(102, "Bob");
Or use custom classes:
Map<String, Product> products = new HashMap<>();
products.put("P001", new Product("Laptop", 999.99));
Just make sure your custom key types implement equals() and hashCode() properly if you're using HashMap.

image quote pre code