- Replies:
- 0
- Words:
- 4858

HashMap
, which we’ll focus on in this guide.
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:
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"
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!";
}
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"
for (String country : capitals.keySet()) {
System.out.println("Country: " + country);
}
for (String city : capitals.values()) {
System.out.println("Capital: "+ city);
}
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.
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"
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