In Java, a Map is an object that stores key-value pairs. Each key in a Map is unique, and each key maps to a single value. This allows for fast lookup, insertion, and deletion of key-value pairs. The Map interface is part of the java.util package and does not extend the Collection interface like most other data structures. It represents a collection of mappings, where each mapping is a relationship between a key and its associated value.
A Map is often used when you need to store and retrieve data based on specific keys, such as:
- Storing user information (e.g., user ID as the key, and user details as the value)
- Counting occurrences of words in a document (e.g., words as keys, and frequency counts as values)
Basic Operations on a Map
- Put: Adds a key-value pair to the map.
- Get: Retrieves the value associated with a given key.
- ContainsKey: Checks if a specific key exists in the map.
- Remove: Removes a key-value pair from the map.
- Size: Returns the number of key-value pairs in the map.
Types of Maps
There are several concrete classes that implement the Map interface in Java. Let’s explore the most commonly used ones:
- HashMap
- LinkedHashMap
- TreeMap
- ConcurrentHashMap