In Java, a Map is an interface in the java.util package that represents a collection of key-value pairs. It provides a way to store data where each value is associated with a unique key.
Key points about Map:
Key-Value Pairs:
Each element in a Map is stored as a key-value pair. The key is used to access the corresponding value.
Unique Keys:
Keys in a Map must be unique. You cannot have duplicate keys.
No Order:
Unlike lists, Maps don't inherently maintain any specific order of elements.
Implementations:
The Map interface is implemented by various classes, such as:
HashMap: Most commonly used implementation, provides fast access to elements.
LinkedHashMap: Maintains the insertion order of elements.
TreeMap: Sorts elements based on their keys' natural ordering or a custom comparator.
ConcurrentHashMap: Thread-safe implementation for concurrent access.
Common operations on a Map:
put(K key, V value): Adds a key-value pair to the map.
get(Object key): Retrieves the value associated with the specified key.
containsKey(Object key): Checks if the map contains a mapping for the specified key.
containsValue(Object value): Checks if the map contains a mapping for the specified value.
remove(Object key): Removes the mapping for the specified key.
size(): Returns the number of key-value pairs in the map.
isEmpty(): Checks if the map is empty.