A Map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
The Map interface is a member of the Java Collections Framework but it does not extend the Collection interface. It represents a different type of collection structure based on key-value pairs.
MapMap is an entry, which consists of a unique key and its corresponding value.Map cannot have duplicate keys. If you try to put a new value with a key that already exists, the old value associated with that key will be replaced.Map interface itself does not guarantee any order. Some implementations, like HashMap, are unordered, while others, like TreeMap (sorted by key) and LinkedHashMap (insertion-ordered), do maintain an order.Map Methods| Method | Description |
|---|---|
V put(K key, V value) |
Associates the specified value with the specified key in this map. |
V get(Object key) |
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
V remove(Object key) |
Removes the mapping for a key from this map if it is present. |
boolean containsKey(Object key) |
Returns true if this map contains a mapping for the specified key. |
boolean containsValue(Object value) |
Returns true if this map maps one or more keys to the specified value. |
int size() |
Returns the number of key-value mappings in this map. |
Set<K> keySet() |
Returns a Set view of the keys contained in this map. |
Collection<V> values() |
Returns a Collection view of the values contained in this map. |
Set<Map.Entry<K, V>> entrySet() |
Returns a Set view of the mappings contained in this map. |
Map ImplementationsThe three most common implementations are:
HashMap: The most widely used Map implementation. It is backed by a hash table. It offers the best performance (O(1) for get and put) but makes no guarantees about order.TreeMap: This implementation stores keys in a sorted order. Its performance is slower (O(log n)) than HashMap.LinkedHashMap: This implementation maintains the insertion order of keys. It provides performance nearly as good as HashMap.Here is an example of how to use a HashMap to store student IDs and names.
import java.util.HashMap; import java.util.Map;public class Main { public static void main(String[] args) { // Declare as a Map, instantiate as a HashMap Map<Integer, String> studentMap = new HashMap<>(); // Add key-value pairs studentMap.put(101, "Alice"); studentMap.put(102, "Bob"); studentMap.put(103, "Charlie"); System.out.println("Map of students: " + studentMap); // Get a value by its key String studentName = studentMap.get(102); System.out.println("Student with ID 102 is: " + studentName); // Remove an entry studentMap.remove(103); System.out.println("Map after removing student 103: " + studentMap); // Loop through the keys System.out.println("--- Looping through keys ---"); for (Integer id : studentMap.keySet()) { System.out.println("ID: " + id + ", Name: " + studentMap.get(id)); } } }
forEach (Java 8+)Prior to Java 8, iterating over a map required getting the entrySet() and using a for-each loop. Java 8 introduced the forEach method, which accepts a BiConsumer (a lambda expression taking two arguments: key and value), making iteration much cleaner.
import java.util.HashMap; import java.util.Map;public class Main { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("USA", "Washington D.C."); capitals.put("Japan", "Tokyo"); capitals.put("France", "Paris"); // Clean, modern iteration using lambda capitals.forEach((country, city) -> { System.out.println("The capital of " + country + " is " + city); }); } }
Java 8 added powerful methods to the Map interface to handle updating or adding values conditionally without writing verbose if-else statements.
computeIfAbsent: Computes a value and inserts it only if the key is not already associated with a value.computeIfPresent: Recomputes the value for a key only if it is already present.merge: If the key doesn't exist, it puts a new value. If it does exist, it uses a provided function to merge the old value with the new one.import java.util.HashMap; import java.util.Map;public class Main { public static void main(String[] args) { Map<String, Integer> inventory = new HashMap<>(); inventory.put("Apples", 10); // Add Bananas only if they don't exist inventory.computeIfAbsent("Bananas", key -> 50); // Increase Apples by 5 if they exist inventory.computeIfPresent("Apples", (key, val) -> val + 5); // Merge: Add 20 to Oranges. If Oranges don't exist, set to 20. inventory.merge("Oranges", 20, (oldVal, newVal) -> oldVal + newVal); inventory.merge("Apples", 20, (oldVal, newVal) -> oldVal + newVal); System.out.println("Inventory: " + inventory); } }
Does a Map allow duplicate keys?