The Map interface in Java is part of the Java Collections Framework and represents a collection of
key-value pairs. Unlike other collection types like List or Set , Map does not extend
the Collection interface.
✅ Key Characteristics of Map :
Stores key-value pairs.
Keys must be unique, but values can be duplicated.
Allows null values and one null key (in HashMap ).
Each key maps to at most one value.
🔧 Commonly Used Implementations:
Class Description
HashMap Fast and allows one null key and multiple null values; no
ordering.
LinkedHashMap Maintains insertion order.
TreeMap Sorted by natural order or custom comparator; does not
allow null keys.
Hashtable Synchronized version of HashMap ; thread-safe, but
outdated.
ConcurrentHashMap Thread-safe and better for concurrent use; no locking entire
map.
🧪 Basic Example:
java Copy Edit
import java.util.*; public class MapExample { public static void main(String[] args) {
Map<String, Integer> marks = new HashMap<>(); // Add elements marks.put("Math", 90);
marks.put("Science", 85); marks.put("English", 92); // Retrieve value
System.out.println("Math Marks: " + marks.get("Math")); // Check key presence
System.out.println("Contains 'Science'? " + marks.containsKey("Science")); // Loop
through entries for (Map.Entry<String, Integer> entry : marks.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue()); } } }
🔍 Useful Methods in Map :
Method Description
put(K key, V value) Inserts or updates value for the key
get(Object key) Returns the value for the key
remove(Object key) Removes the entry for the key
containsKey(Object key) Checks if the key exists
containsValue(Object value) Checks if the value exists
keySet() Returns a set of all keys
values() Returns a collection of all values
entrySet() Returns a set of key-value mappings