The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
In Core Java, the Map
interface is a part of the Java Collections Framework and is used to represent a collection of key-value pairs where each key is associated with exactly one value. It is designed to model the mathematical function abstraction and allows you to perform operations based on keys, such as adding a key-value pair, removing a key-value pair, and retrieving the value associated with a given key.
The Map
interface is part of the java.util
package, and some of the commonly used implementing classes are HashMap
, TreeMap
, LinkedHashMap
, and HashTable
. Each implementing class has its own characteristics, such as ordering of elements, synchronization, and performance characteristics.
Here’s a brief overview of some key methods in the Map
interface:
put(key, value)
: Adds a key-value pair to the map.get(key)
: Retrieves the value associated with a given key.remove(key)
: Removes the key-value pair associated with the specified key.containsKey(key)
: Checks if the map contains a specific key.containsValue(value)
: Checks if the map contains a specific value.keySet()
: Returns a set of all keys in the map.values()
: Returns a collection of all values in the map.entrySet()
: Returns a set of key-value pairs (entries) in the map.
An example of using the Map
interface with a HashMap
implementation:
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// Creating a HashMap
Map<String, Integer> map = new HashMap<>();
// Adding key-value pairs
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
// Retrieving values
System.out.println("Value for key 'Two': " + map.get("Two"));
// Checking if a key exists
System.out.println("Contains key 'Four': " + map.containsKey("Four"));
// Iterating through key-value pairs
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
In this example, a HashMap
is used to store key-value pairs, and various operations are performed using the Map
interface methods.