Java Program to create a HashMap and add key-value pairs

Java 8Object Oriented ProgrammingProgramming

To create a HashMap, use the HashMap class −

HashMap hm = new HashMap();

Add elements to the HashMap in the form of key-value pair −

hm.put("Bag", new Integer(1100));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));

The following is an example to create HashMap and add key-value pair −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
   }
}

Output

Belt: 600
Wallet: 700
Bag: 1100
raja
Published on 11-Jan-2019 12:07:22
Advertisements