What is Map

What is Map

Answer: Map is an interface which maps unique keys with its values. Key is object which you will use to retrieve value later time. Using key and value pair you store value in the Map object and once its value stored can be retrieved by using its key. In java API Map is a generic which declared as below:

interface Map<K, V>

K specifies type of keys
V specifies type of values

Please use JAVA API document link to see its method details here: Map API oracle documentation

Maps got two basic and very useful method: get( ) and put( ). To store value into map
use put( ) using key and value. To extract its value call get( ) and pass key as argument then value will be returned.

Important: Map is not part of collection framework because it does not implement Collection interface. Although we can obtain collection view of map using entrySet method which returns Set that contains elements in Map. To extract collection view of keys use keySet( ). To extract collection view of values use values( ).

Below is example java class shows example of map:

package com.javahonk.setTest;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HashMapIteration {

    public static void main(String[] args) {

    Map<String, String> map = new HashMap<String, String>();

    map.put("1", "First");
    map.put("2", "Second");
    map.put("3", "Third");
    map.put("4", "Fourth");
    map.put("5", "Five");

    System.out.println("Iterator Example 1\n");

    Iterator<Entry<String, String>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String,String> entry = (Map.Entry<String,String>) it.next();
        String key = (String) entry.getKey();
        String val = (String) entry.getValue();
        System.out.println("Key:" + key + ",Value: " + val);        

    System.out.println("\nIterator Example 2\n");

    Iterator<String> iterator = map.keySet().iterator();
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        String val = (String) map.get(key);
        System.out.println("Key:" + key + ",Value: " + val);        

    System.out.println("\nMap.Entry Example 3\n");

    for (Map.Entry<String,String> entry : map.entrySet()) {
        System.out.println("Key:" + entry.getKey() + ",Value: "
                + entry.getValue());        

            .println("\nExample 4"
                    + ". If you're only interested in the keys, "
                    + "you can iterate through the keySet() of the map:\n");

    for (String key : map.keySet()) {
        System.out.println("Key:" + key);

    System.out.println("\nExample 5"
            + ". If you only need the values, use values():\n");
    for (Object value : map.values()) {
        System.out.println("Value:" + value);





What is Map

Leave a Reply

Your email address will not be published. Required fields are marked *