Home‎ > ‎Applied Core Java‎ > ‎Collection Framework‎ > ‎


Problem : Create a dynamic HashMap that contains key-value pairs.

Program :

Step 1 - Coding

Create a text file c:\sunilos\TestHashMap.java  and copy below contents.

import java.util.*;

 * A program of HashMap.

public class TestHashMap {

    public static void main(String[] args) {

        HashMap hMap = new HashMap();

        // Below HashMap contains RollNo and their respective marks

        hMap.put("RN1001", new Integer(890));
        hMap.put("RN1002", new Integer(900));
        hMap.put("RN1003", new Integer(780));
        hMap.put("RN1004", new Integer(950));

         * You can insert any object in the HashMap. Primitive data type need to
         * be converted into Objects before inserting.

        // Display the size of Map
        System.out.println("Size of Map is " + hMap.size());

        Object obj = hMap.get("RN1002");
        // Display the value of given key
        System.out.println("Value of Index # = " + obj);

        // Remove the value of given key
        System.out.println("Remove the value of given key "
                + hMap.remove("RN1002"));

         // Will remove all elements

        // Show that HashMap is Empty or not
        System.out.println("Is Empty :-" + hMap.isEmpty());



Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy TestHashMap.java  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile TestHashMap.java with help of 
    • javac TestHashMap.java command. Compiled class file will be created in the same folder
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java TestHashMap command.


Size of Map is 4
Value of Index # = 900
Remove the value of given key 900
Is Empty :-true

<<Previous | Next>>
Namrata Sisodiya,
Aug 19, 2011, 1:07 AM