Map Collection Tutorial for Java Beginners

Map is an Interface which comes under Java Collection framework.

Main Characteristic of Map Interface

  • It is an Object that used to map keys to values.
  • A Map cannot contain Duplicate values.
  • Every key can map to one value at most.
  • This interface is replacement to Dictionary class which was an abstract class instead of Interface.
  • Map interface allows 3 collection views
    • Set of keys
    • Collection of values
    • Set of key-value mappings
  • As Map provide 3 views as above, It allows you to iterate over keys, values or key value pair.
  • Entry can be removed from a Map in a safe way during iteration.
  • It is not permissible for a map to contain itself as a key.
  • Map can contain itself as value.
  • There are some restriction on the keys and values some map implementation can contain.
  • Attempting to insert an ineligible key or value throws an unchecked exception.

 

Concrete Map Implementation

  • HashMap
  • Hashtable
  • EnumMap
  • IdentityHashMap
  • LinkedHashMap
  • Properties
  • TreeMap
  • WeakHashMap
  • ConcurrentSkipListMap
  • ConcurrentHashMap

Important Methods in Map Interface

  • put(K key, V value) : Put the specified value in map with specified key.
  • putAll(Map<? extends K, ? extends V> m) : Copies all mapping from given Map to this Map.
  • keySet() : Returns a Set containing the key in this Map.
  • values() : Returns a Collection containing all values in this Map.
  • isEmpty() : Check if there is any element in given Map or not.
  • remove(Object key) : Removes the mapping for a key from this map if it is present.
  • containsKey(Object key) : Checks if there any mapping for specified key.
  • containsValue(Object value) : Checks if there any mapping for specified Object (Could be more than one).
  • get(Object key) : Returns the value to which this key is associated to.
  • clear() : Used to remove all the mapping in given Map.

     

 

By | 2017-07-09T12:13:17+00:00 February 16th, 2013|Core Java|2 Comments

About the Author:

2 Comments

  1. Michael November 22, 2014 at 5:19 am - Reply

    Nice blog! very educative and easy to understand. But some of your posts are incomplete.
    e.g exception and thread.
    Pls can you tell me the difference between HashMap and HashTable?
    Thanks

  2. kishore October 4, 2016 at 12:09 pm - Reply

    It will be useful if u add some example programs for each topics.

Leave A Comment