Map Interface

A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. Map maps unique keys to values.Map is useful in case of search, update or delete elements on the basis of key. Below are few methods declared in the Map interface. They are as follows:

Method Role
public Object put(Object key, Object value) Insert a value in the map.
public void putAll(Map map) Insert the given map in the map.
public Object remove(Object key) Remove an element for the specified key.
public Object get(Object key) Return the value for the specified key.
public boolean containsKey(Object key) Search the specified key from the map.
public Set keySet()  Return the Set view containing all the keys.
public Set entrySet() Return the Set view containing all the keys and values.
public int size() Return total number of key/value pair in the map.
public boolean isEmpty()  Check if map is empty.

Let us see an example:

package collectionFramework;

import java.util.HashMap;
import java.util.Map;

public class MapTest {

  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(1, "Ankit");
    map.put(2, "Ishwar");
    map.put(3, "Arjun");
    
    for(Map.Entry me:map.entrySet()) {
      System.out.println("Key -> " + me.getKey()+" Value -> " + me.getValue());
    }
  }

Output:

Key -> 1 Value -> Ankit
Key -> 2 Value -> Ishwar
Key -> 3 Value -> Arjun