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.
The Map interface defines basic operations like adding, removing, and retrieving elements using keys.
// Map interface syntax declaration
Map<Key, Value> map = new HashMap<>();
// 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);
}
}
The program stores student IDs as keys and names as values. When printed, the map displays all key-value pairs in no guaranteed order.
Enter a Key and Value to simulate map.put(). Notice how duplicate keys update the existing value!
HashMap for fast accessTreeMap when sorted keys are required