Map Interface in Java

Naveen AnamaneniUpdated · 5 min read

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

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

ClassOrder of keysnull keysInternal structure
HashMapNo orderOne allowedHash table
LinkedHashMapInsertion (or access) orderOne allowedHash table plus linked list
TreeMapSorted by keyNot allowedRed-black tree
HashtableNo orderNot allowedSynchronized hash table (legacy)
EnumMapEnum declaration orderNot allowedArray

Methods of Map

MethodDescription
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.

MapDemo.java▶ Try it
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());
    }
}
Output
{Navika=91, Srihitha=78, Advitha=85}
Srihitha: 78
Old value: 78
Has Advitha? true
Unknown: null
{Navika=91, Srihitha=88}, size 2

Explanation: 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

Views.java▶ Try it
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());
    }
}
Output
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

  1. Easy: Store five country-capital pairs in a map and print the capital of a country the user types.
  2. Harder: Build a phone book map from names to lists of phone numbers, where one person can have several numbers.

Quick check: Map interface

4 questions
1What happens when you put a value for an existing key?
2What does get return for a missing key?
3Does Map extend Collection?
4Which method returns all the keys?

Key Takeaways

Was this tutorial helpful?

Lesson 280 of 482