Java Map Interface
# Java Map Interface
The Map interface provides a one-to-one mapping between keys and values. You can retrieve a value using its corresponding key.
* Given a key and a value, you can store the value in a Map object. Later, you can access the corresponding value using the key.
* When the accessed value does not exist, the method throws a `NoSuchElementException`.
* When the type of the object is incompatible with the element types in the Map, a `ClassCastException` is thrown.
* When using a null object in a Map that does not allow null objects, a `NullPointerException` is thrown.
* When attempting to modify a read-only Map, an `UnsupportedOperationException` is thrown.
| No. | Method Description |
| --- | --- |
| 1 | void clear( ) Removes all mappings from this map (optional operation). |
| 2 | boolean containsKey(Object k) Returns true if this map contains a mapping for the specified key. |
| 3 | boolean containsValue(Object v) Returns true if this map maps one or more keys to the specified value. |
| 4 | Set entrySet( ) Returns a Set view of the mappings contained in this map. |
| 5 | boolean equals(Object obj) Compares the specified object with this map for equality. |
| 6 | Object get(Object k) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
| 7 | int hashCode( ) Returns the hash code value for this map. |
| 8 | boolean isEmpty( ) Returns true if this map contains no key-value mappings. |
| 9 | Set keySet( ) Returns a Set view of the keys contained in this map. |
| 10 | Object put(Object k, Object v) Associates the specified value with the specified key in this map (optional operation). |
| 11 | void putAll(Map m) Copies all of the mappings from the specified map to this map (optional operation). |
| 12 | Object remove(Object k) Removes the mapping for a key from this map if it is present (optional operation). |
| 13 | int size( ) Returns the number of key-value mappings in this map. |
| 14 | Collection values( ) Returns a Collection view of the values contained in this map. |
### Example
The following example demonstrates the functionality of Map.
```java
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
m1.put("Daisy", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("t" + m1);
}
}
The compilation and execution result of the above example is as follows:
Map Elements
{Mahnaz=31, Ayan=12, Daisy=14, Zara=8}
YouTip