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)); } } }