Map interface Methods Java

After knowing what Map is and its position in the collections hierarchy diagram, let us explore the methods. These methods can be used straight way by its derived data structures like TreeMap and HashMap.

Following are the important Map interface Methods
  1. boolean containsKey(Object key1): Used to check the availability of a specific key, key1, in the map. Returns true if the map includes the key key1.
  2. boolean containsValue(Object value1): Used to check the availability of a specific value, value1, in the map. Returns true if the map includes the value value1.
  3. Object get(Object key1): Returns the value associated with the key, key1. Important method to get the value of a key.
  4. Object put(Object key1, Object value1): Add the key/value pair key1/value1 to the map. If the key key1 already exists, it is replaced by the new value value1. Remember, the keys cannot be in duplicates. One key can map to only one value. Two same values can be mapped by two different keys. If addition is successful, the method returns the key object.
  5. Object remove(Object key1): Deletes the key key1 from the map. If the removal is successful, it returns the value of the key removed.
  6. void putAll(Map m1): Used to place the key/value pairs of one map into another; a very easy way to copy elements data to another map.
  7. Set keySet(): Returns the entire keys of the map as a Set object. Returning a Set object is quiet reasonable as Set does not allow duplicates (also map does not allow duplicate keys).
  8. Collection values(): Returns a collection object that contains the entire values of the map. Returning a collection object is quiet reasonable as collection classes (except Set classes) allow duplicates (also map permits duplicate values; a value like red can mapped by two keys like apple and cherry).
  9. boolean equals(Object obj): Used to check whether two map objects contain the same key/value pairs (here, order is not important).
  10. int size(): Returns the number of key/value pairs stored.
  11. boolean isEmpty(): Returns true if the map does not have any elements.
  12. void clear(): Deletes all the elements of the map at a single stroke (without calling remove() method number of times).

There are two important implemented classes (concrete subclasses) for Map interface – HashMap and TreeMap. When elements (in map, an element is a key/value pair) are added or deleted consistently (very often), prefer HashMap. If the addition and deletion operations are done less times, prefer TreeMap and added advantage is TreeMap traverses the keys very fast in sorted order; there by, retrieval is fast.

Programming Tip: Internally Map maintain keys in the form of a Set (thereby no duplicates) and values in the form of a Collection class like a List (thereby duplicates allowed).

Pass your comments and suggestions to improve this tutorial "Map interface Methods".

Leave a Comment

Your email address will not be published.