Back to Study Material Java

Map Interface in Java

The Map interface in Java is part of the java.util package and represents a collection that stores data as key-value pairs. Unlike List or Set, a Map does ...

Map Interface in Java

What Is the Map Interface?

The Map interface in Java is part of the java.util package and represents a collection that stores data as key-value pairs. Unlike List or Set, a Map does not extend the Collection interface directly. Instead, it defines its own contract for storing, retrieving, and managing entries where each key maps to exactly one value. No two entries in a Map can share the same key, though multiple keys can point to the same value.

The Map interface declares methods such as put(K key, V value) to add entries, get(Object key) to fetch a value, remove(Object key) to delete an entry, and containsKey(Object key) to check existence. It also provides views of its content through keySet(), values(), and entrySet(), which return a Set of keys, a Collection of values, and a Set of Map.Entry objects respectively.

Common implementations include HashMap, LinkedHashMap, and TreeMap. Each offers different behaviors in terms of ordering and performance. HashMap is unordered and fastest for lookups, LinkedHashMap maintains insertion order, and TreeMap keeps keys sorted.

A simple usage looks like this:

Map<String, Integer> scores = new HashMap<>(); scores.put("Alice", 95); scores.put("Bob", 87); System.out.println(scores.get("Alice")); // 95

When iterating, entrySet() is the most efficient choice because it avoids a second lookup for each value. Use a for-each loop over entrySet() instead of calling get() inside a keySet() loop.

Interview tip: Interviewers often ask the difference between Map and Collection. The key answer is that Map stores key-value pairs while Collection stores individual elements, and Map does not inherit from Collection.

Understanding the Map interface is essential before diving into its implementations, since all Map classes share this common contract. Mastering its methods lets you work with any Map implementation interchangeably.