Mastering maps in Java is one of the most essential and frequently used skills in any Java tutorial for beginners — maps let you store key-value pairs (like a dictionary), where each unique key maps to exactly one value. This makes maps in Java perfect for real-world tasks: user sessions, configuration settings, caching, lookups, grouping data, counting frequencies, and building fast search structures. In 2025–2026, maps remain a core part of every Java developer’s toolkit — used everywhere from Android apps to Spring Boot backends and big data processing.
In this complete maps in Java guide, you’ll focus on the most popular implementation: HashMap (from java.util). You’ll learn how to:
- Create and initialize maps
- Add, update, remove, and access entries
- Loop through keys, values, and entries
- Use powerful Map methods (getOrDefault, containsKey, keySet, values, etc.)
- Understand why HashMap > alternatives in most cases
- Avoid common beginner mistakes
All examples are tested in jshell (Java’s REPL) — copy-paste to see instant results on Java 21 (LTS in 2025–2026).
Prerequisites
- Java 11+ installed (preferably 17 or 21 LTS)
- Ubuntu: sudo apt install openjdk-21-jdk
- Windows/macOS: https://adoptium.net/
- Terminal + jshell (type jshell to start)
- Basic knowledge of variables, data types, loops & conditionals
1. Creating Maps in Java – HashMap Basics
Import first:
import java.util.HashMap;
import java.util.Map;
Way 1 – Empty map
Map capitals = new HashMap<>();
Way 2 – With initial values (Java 9+)
Map scores = Map.of("Zain", 95, "Ali", 88, "Sara", 92);
Way 3 – From another map or collection
Map config = new HashMap<>();
config.put("theme", "dark");
config.put("language", "en");
Generic types <String, Integer> ensure type safety — only allowed keys/values.
2. Adding & Updating Entries – Core of Maps in Java
Map capitals = new HashMap<>();
// Add new entry
capitals.put("Pakistan", "Islamabad");
capitals.put("France", "Paris");
// Update existing key
capitals.put("France", "Lyon"); // overwrites Paris → Lyon
// Add if key doesn't exist (Java 8+)
capitals.putIfAbsent("Japan", "Tokyo");
// Add multiple
capitals.putAll(Map.of("Germany", "Berlin", "Italy", "Rome"));
Check size & emptiness:
System.out.println(capitals.size()); // 4
System.out.println(capitals.isEmpty()); // false
3. Accessing & Checking Entries
String capital = capitals.get("Pakistan"); // Islamabad
String missing = capitals.get("Spain"); // null
// Safe get with default (Java 8+)
String safe = capitals.getOrDefault("Spain", "Not found");
System.out.println(safe); // Not found
Existence checks:
System.out.println(capitals.containsKey("Italy")); // true
System.out.println(capitals.containsValue("Rome")); // true
4. Removing Entries from Maps in Java
capitals.remove("France"); // removes key + value
// Remove if value matches
capitals.remove("Germany", "Berlin"); // removes only if value is exact
// Clear all
// capitals.clear();
5. Looping Through Maps in Java
Loop keys:
for (String country : capitals.keySet()) {
System.out.println("Country: " + country);
}
Loop values:
for (String city : capitals.values()) {
System.out.println("Capital: " + city);
}
Loop entries (key + value – most useful):
for (Map.Entry entry : capitals.entrySet()) {
System.out.println(entry.getKey() + " → " + entry.getValue());
}
Modern forEach (Java 8+):
capitals.forEach((country, city) ->
System.out.println(country + " → " + city));
6. Best Practices & Modern Tips (2025–2026)
- Always use interface Map<String, String> on left, concrete HashMap<> on right
- Prefer Map.of(…) (Java 9+) for small, immutable maps
- Use var (Java 10+) for cleaner declarations:
var users = new HashMap();
- Avoid null keys/values when possible — use Optional or defaults
- Use LinkedHashMap when insertion order matters
- Use ConcurrentHashMap for thread-safe maps
- Use computeIfAbsent (Java 8+) for lazy initialization:
capitals.computeIfAbsent("Brazil", k -> "Brasília");
Maps in Java – FAQ (2025–2026)
- How do I create maps in Java?Map<String, String> map = new HashMap<>(); or Map.of(“key”, “value”) (immutable)
- How do I add/remove entries in maps in Java?
put(key, value), putIfAbsent, remove(key), remove(key, value) - How do I loop through maps in Java?
Best: map.forEach((k,v) -> …) or for (var entry : map.entrySet()) - What’s the difference between HashMap & LinkedHashMap?
HashMap: fastest, no order; LinkedHashMap: preserves insertion order - How do I get a value safely in maps in Java?
map.getOrDefault(key, defaultValue)
Summary
You now fully understand maps in Java: HashMap creation, add/remove/update, access/check, looping, powerful methods (getOrDefault, containsKey, keySet, forEach, etc.), and best practices.
Mastering maps in Java unlocks fast lookups, grouping, caching, configuration, and almost every real Java program.