Map Interface in Java
The Map interface in Java is used to store data as key-value pairs. Each key is linked to exactly one value, like a word and its meaning in a dictionary, or a roll number and a student's name. Keys are unique: putting a value for a key that already exists replaces the old value. Values may be repeated. Map is part of the Collections Framework but does not extend Collection, because it holds pairs rather than single elements. In this lesson, you will learn the features of Map, its implementations and its main methods.
Declaration
public interface Map<K, V>K is the type of the keys and V is the type of the values. For example, Map<String, Integer> maps names to marks.
Features of Map
- Key-value pairs: every entry has a key and a value.
- Unique keys: one key maps to at most one value.
- Duplicate values are fine: two keys can have the same value.
- Fast lookup by key: in a
HashMap, finding a value by its key takes constant time on average. - Not a
Collection: but it offers collection views of its keys, values and entries.
Implementation Classes
| Class | Order of keys | null keys | Internal structure |
|---|---|---|---|
HashMap | No order | One allowed | Hash table |
LinkedHashMap | Insertion (or access) order | One allowed | Hash table plus linked list |
TreeMap | Sorted by key | Not allowed | Red-black tree |
Hashtable | No order | Not allowed | Synchronized hash table (legacy) |
EnumMap | Enum declaration order | Not allowed | Array |
Methods of Map
| Method | Description |
|---|---|
V put(K key, V value) | It is used to add a pair, or replace the value of an existing key. It returns the old value or null. |
V get(Object key) | It returns the value for the key, or null if the key is absent. |
V remove(Object key) | It removes the pair and returns its value. |
boolean containsKey(Object key) | It returns true if the key is present. |
boolean containsValue(Object value) | It returns true if some key maps to the value. |
int size() | It returns the number of pairs. |
Set<K> keySet() | It returns a set view of the keys. |
Collection<V> values() | It returns a collection view of the values. |
Set<Map.Entry<K, V>> entrySet() | It returns a set view of the pairs. |
static Map<K, V> of(...) | It returns an unmodifiable map. |
Example: Basic Map Operations
Let's see an example that stores the marks of students.
import java.util.LinkedHashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> marks = new LinkedHashMap<>();
marks.put("Navika", 91);
marks.put("Srihitha", 78);
marks.put("Advitha", 85);
System.out.println(marks);
System.out.println("Srihitha: " + marks.get("Srihitha"));
System.out.println("Old value: " + marks.put("Srihitha", 88));
System.out.println("Has Advitha? " + marks.containsKey("Advitha"));
System.out.println("Unknown: " + marks.get("Anamaneni"));
marks.remove("Advitha");
System.out.println(marks + ", size " + marks.size());
}
}{Navika=91, Srihitha=78, Advitha=85}
Srihitha: 78
Old value: 78
Has Advitha? true
Unknown: null
{Navika=91, Srihitha=88}, size 2Explanation: put adds three pairs. Putting a new value for "Srihitha" replaces 78 with 88 and returns the old 78; the key isn't duplicated. get for a missing key returns null. A LinkedHashMap is used so the printed order matches the insertion order.
Example: The Three Views
import java.util.Map;
import java.util.TreeMap;
public class Views {
public static void main(String[] args) {
Map<String, Integer> marks = new TreeMap<>(
Map.of("Navika", 91, "Srihitha", 78, "Advitha", 85));
System.out.println("Keys: " + marks.keySet());
System.out.println("Values: " + marks.values());
System.out.println("Entries: " + marks.entrySet());
}
}Keys: [Advitha, Navika, Srihitha]
Values: [85, 91, 78]
Entries: [Advitha=85, Navika=91, Srihitha=78]Explanation: keySet, values and entrySet return views of the map. A TreeMap keeps keys sorted, so all three views follow the alphabetical order of the names. Looping over these views is covered in "Map.Entry and Iterating Over Maps".
Common Mistakes
Expecting put to add a second value for the same key. It replaces the value; use Map<K, List<V>> for many values per key.
Unboxing get into an int for a missing key. int m = marks.get("x"); throws NullPointerException.
Assuming a HashMap keeps insertion order. Use LinkedHashMap for that.
Interview Corner
Why doesn't Map extend the Collection interface?
A Collection is a group of single elements with methods like add(E), while a Map holds key-value pairs and works with put(K, V) and lookups by key. The two models don't fit one interface. Instead, Map provides collection views: keySet(), values() and entrySet().
Practice
- Easy: Store five country-capital pairs in a map and print the capital of a country the user types.
- Harder: Build a phone book map from names to lists of phone numbers, where one person can have several numbers.
Key Takeaways
Was this tutorial helpful?