Java Map Interface
In the Map interface, keys and values are mapped one-to-one. You can retrieve a value through its key.
- Given a key and a value, you can store that value in a Map object. Afterwards, you can access the corresponding value through 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 type in the Map, a ClassCastException is thrown.
- When a Null object is used 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; returns 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 illustrates the functionality of Map
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 results of the above example are as follows:
Map Elements
{Mahnaz=31, Ayan=12, Daisy=14, Zara=8}