Latest web development tutorials

Java Map Interface

Map interface keys and values-one mapping. You can get the value by key.

  • Given a key and a value, you can store the value after a Map object, you can access the corresponding value through the key.
  • When the value of access does not exist, the method will throw an exception NoSuchElementException.
  • When the object type and in the Map element type is not compatible with the time, it will throw a ClassCastException.
  • When using Null Null objects are not allowed in the Map object, throws a NullPointerException.
  • When the attempt to modify a read-only Map, throws an UnsupportedOperationException.
No. Method Description
1 void clear ()
Removes all of the mappings (optional) map.
2 boolean containsKey (Object k)
If this map contains a mapping between the specified key, it returns true.
3 boolean containsValue (Object v)
If this map maps one or more keys to the specified value, it returns true.
4 Set entrySet ()
Back 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 of the specified key is mapped; if this map contains no mapping for the key, it returns null.
7 int hashCode ()
Returns the hash code value for this map.
8 boolean isEmpty ()
If this map contains no key - value mappings, it returns true.
9 Set keySet ()
Back Set view this map contains keys.
10 Object put (Object k, Object v)
Associated with the specified key to the specified value to this map (optional operation).
11 void putAll (Map m)
Copy specify the mapping in all of the mappings from this map (optional operation).
12 Object remove (Object k)
If there is a mapping between keys, it is removed from (optional) map.
13 int size ()
Returns map key - value mappings.
14 Collection values ​​()
Returns a Collection view of the values ​​contained in this map.

Examples

The following example to explain the function 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 above examples compiled results are as follows:

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