In Java, the Map Interface is part of the java.util package and represents a collection of key-value pairs, where Keys should be unique, but values can be duplicated.
- It provides efficient retrieval, insertion, and deletion operations based on keys.
- HashMap and LinkedHashMap allow one null key, and TreeMap does NOT allow null keys (if natural ordering is used).
- Use ConcurrentHashMap for thread-safe operations, or Collections.synchronizedMap() to make an existing map synchronized.
Declaration of the Map interface
public interface Map<K, V>
- K -> Type of keys maintained by the map
- V -> Type of mapped values
Creating Map Objects
Since a Map is an interface, we cannot create its object directly. We must use a class that implements it (e.g., HashMap).
Map<String, Integer> hm = new HashMap<>();
import java.util.HashMap;
import java.util.Map;
public class Geeks{
public static void main(String[] args){
// Create a Map using HashMap
Map<String, Integer> m = new HashMap<>();
// Adding key-value pairs to the map
m.put("Geek1", 1);
m.put("Geek2", 2);
m.put("Geek3", 3);
System.out.println("Map elements: " + m);
}
}
Output
Map elements: {Geek3=3, Geek2=2, Geek1=1}
Hierarchy of Map
It is part of the Java Collections Framework, and its key implementation classes include HashMap, LinkedHashMap, TreeMap, and Hashtable.