Map
Map is an interface in the Collection Framework that stores data as key-value pairs. Every key is unique, and it's linked directly to one specific value, allowing quick lookup of a value using its key.
1. What is a Map?
Map is an interface in the Collection Framework that stores data as key-value pairs. Every key is unique, and it's linked directly to one specific value, allowing quick lookup of a value using its key.
2. Why is it used?
Map is ideal when data naturally comes in pairs — like a student's roll number (key) linked to their name (value), letting you retrieve information quickly using just the key.
3. Real-Life Example
Think of a phonebook, where each contact name (key) is linked to a specific phone number (value). You look up a phone number directly by the name, without scanning through every entry.
4. Syntax
javaMap<KeyType, ValueType> mapName = new HashMap<>(); // or LinkedHashMap, TreeMap
5. Example Program
javaimport java.util.Map; import java.util.HashMap; public class MapDemo { public static void main(String[] args) { Map<Integer, String> students = new HashMap<>(); students.put(1, "Aman"); students.put(2, "Neha"); System.out.println(students.get(1)); } }
Output:
Aman6. Key Points to Remember
Mapstores data as key-value pairs, and keys must be unique (values can repeat).Mapdoes not extend theCollectioninterface, unlikeListandSet.- Common implementations include
HashMap,LinkedHashMap, andTreeMap.