Map (HashMap)
A Map is an interface in the Java Collections Framework that stores key-value pairs. HashMap is the most common implementation — it uses a hash table for O(1) average access. A Map does not allow duplicate keys, but values may be duplicated.
Besides HashMap, Java also provides LinkedHashMap (preserves insertion order), TreeMap (sorted by natural/Comparator key order), Hashtable (legacy, thread-safe), and ConcurrentHashMap (thread-safe, high performance). Choose the appropriate implementation based on your needs for ordering, thread safety, and performance.
Java 9+ provides the factory methods Map.of(), Map.copyOf(), and Map.ofEntries() for compact immutable map creation. Map.Entry allows iterating over key-value pairs together.
Map Implementations:
| Class | Ordering | Thread-Safe | Use |
|---|---|---|---|
HashMap |
Unordered | No | General purpose, high performance |
LinkedHashMap |
Insertion order | No | When you need insertion order |
TreeMap |
Sorted by key | No | When you need natural ordering |
ConcurrentHashMap |
Unordered | Yes | Multithreading |
Hashtable |
Unordered | Yes (legacy) | Avoid; use ConcurrentHashMap instead |
Code Example
import java.util.HashMap;
import java.util.Map;
public class MapJava {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> price = new HashMap<>();
price.put("Apple", 5000);
price.put("Mango", 8000);
price.put("Orange", 6000);
price.put("Banana", 4000);
System.out.println("Prices: " + price);
// Access a value
System.out.println("Apple price: " + price.get("Apple"));
// Check keys/values
System.out.println("Has Mango? " + price.containsKey("Mango"));
System.out.println("Has price 7000? " + price.containsValue(7000));
// Update
price.put("Apple", 5500); // update
price.put("Mango", 25000); // add new
// Iterate
for (Map.Entry<String, Integer> entry : price.entrySet()) {
System.out.println(entry.getKey() + " = $" + entry.getValue());
}
// Java 9+ factory method
Map<String, Integer> priceFix = Map.of(
"Apple", 5000,
"Mango", 8000,
"Orange", 6000
);
System.out.println("Immutable map: " + priceFix);
}
}
Code Explanation
new HashMap<>()creates an empty map with generic types<String, Integer>— keys of type String, values of type Integer.put(key, value)adds or updates a key-value pair. If the key already exists, the old value is replaced.get(key)retrieves a value by key. Returnsnullif the key is not found.containsKey()andcontainsValue()check for the presence of a specific key/value.entrySet()returns a Set containing all key-value pairs, which can be iterated with for-each.Map.of()(Java 9+) creates an immutable map — it cannot be modified after creation.
Everyday Example
A word frequency counter program for a piece of text:
import java.util.HashMap;
import java.util.Map;
public class WordFrequency {
public static void main(String[] args) {
String text = "java is a powerful language java is easy to learn";
String[] word = text.split(" ");
Map<String, Integer> frequency = new HashMap<>();
for (String k : word) {
frequency.merge(k, 1, Integer::sum);
}
System.out.println("=== Word Frequency ===");
for (Map.Entry<String, Integer> entry : frequency.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue() + "x");
}
}
}
Summary
Maps are a fundamental data structure for key-value data. HashMap is the default choice for most cases. Use LinkedHashMap when you need insertion order, TreeMap when you need sorted order, and ConcurrentHashMap for multithreading. Also master merge(), computeIfAbsent(), and other modern methods.