← Back to Chapters

Map Interface in Java

?️ Map Interface in Java

? Quick Overview

The Map interface in Java is part of the java.util package. It stores data in key–value pairs, where each key is unique and mapped to a single value.

? Key Concepts

  • Keys are unique, values can be duplicated
  • Map is not a child of Collection interface
  • Common implementations: HashMap, LinkedHashMap, TreeMap
  • Fast data retrieval using keys

? Syntax & Theory

The Map interface defines basic operations like adding, removing, and retrieving elements using keys.

? View Code Example
// Map interface syntax declaration
Map<Key, Value> map = new HashMap<>();

? Code Example

? View Code Example
// Demonstrating basic Map operations
import java.util.HashMap;
import java.util.Map;

public class MapExample {
public static void main(String[] args) {
Map<Integer, String> students = new HashMap<>();

students.put(1, "Amit");
students.put(2, "Ravi");
students.put(3, "Sita");

System.out.println(students);
}
}

? Output / Explanation

The program stores student IDs as keys and names as values. When printed, the map displays all key-value pairs in no guaranteed order.

? Interactive Map Playground

Enter a Key and Value to simulate map.put(). Notice how duplicate keys update the existing value!

Map is empty {}
// Action log will appear here...

? Tips & Best Practices

  • Use HashMap for fast access
  • Use TreeMap when sorted keys are required
  • Avoid using mutable objects as keys

? Try It Yourself

  • Create a Map to store employee ID and salary
  • Replace HashMap with LinkedHashMap and observe output order
  • Iterate over Map using entrySet()