java.util.Map is an interface that represents a collection of key-value pairs. It’s part of the Java Collections Framework and provides methods to manipulate and access elements based on their keys.
java.util.Map interface in Java provides several methods to work with key-value pairs. Here are some of the important methods defined by the
- Basic Operations:
V put(K key, V value): Associates the specified value with the specified key in the map. If the map previously contained a mapping for the key, the old value is replaced.
V get(Object key): Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
boolean containsKey(Object key): Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value): Returns true if this map maps one or more keys to the specified value.
V remove(Object key): Removes the mapping for the specified key from this map if present.
void clear(): Removes all of the mappings from this map.
int size(): Returns the number of key-value mappings in this map.
boolean isEmpty(): Returns true if this map contains no key-value mappings.
- Bulk Operations:
void putAll(Map<? extends K, ? extends V> m): Copies all of the mappings from the specified map to this map.
void replaceAll(BiFunction<? super K, ? super V, ? extends V> function): Replaces each entry’s value with the result of applying the given function.
- View Operations:
Set<K> keySet(): Returns a set view of the keys contained in this map.
Collection<V> values(): Returns a collection view of the values contained in this map.
Set<Map.Entry<K, V>> entrySet(): Returns a set view of the mappings contained in this map.
In Java, the
Map interface is implemented by several classes that provide different functionalities and characteristics. Here are some of the common child classes that implement the
Map interface in Java
Difference between HashMap, TreeMap and Hashtable
|Null keys/values||allowed||not allowed||not allowed|
|Synchronised||not synchronized||not synchronized||synchronized|