Java Map Interface

In the Map interface, keys and values are mapped one-to-one. Values can be obtained through keys.

  • Given a key and a value, you can store that value in a Map object. Later, you can access the corresponding value through the key.
  • When the accessed value does not exist, the method throws a NoSuchElementException exception.
  • When the object's type is incompatible with the element types in the Map, a ClassCastException exception is thrown.
  • When a Null object is used in a Map that does not allow Null objects, a NullPointerException exception is thrown.
  • When attempting to modify a read-only Map, an UnsupportedOperationException exception 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 mapped by the specified key; returns null if this map contains no mapping for the key.
7 int hashCode( )
Returns the hash code value of 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 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 exists (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 result of compiling and running the above example is as follows:

Map Elements
        {Mahnaz=31, Ayan=12, Daisy=14, Zara=8}
Other Extensions