HashMap with Example

HashMap : The combination of a key and a value is called a mapping.The map stores the mappings based on the key part of the mapping, in a way similar to how a Set collection stores its elements.The map uses keys to quickly locate associated values.HashMap stores keys according to their hash codes, just like HashSet stores its elements. 

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

public class HashMapExample {

 public static void main(String[] arr) {

  /* Create object of HashMap */
  Map mapObj = 
   new HashMap();

  /* Add value in HashMap */
  mapObj.put(new Integer(1), "One");
  mapObj.put(new Integer(2), "Two");
  mapObj.put(new Integer(5), "Five");
  mapObj.put(new Integer(3), "Three");
  mapObj.put(new Integer(4), "Four");
  mapObj.put(new Integer(8), "Eight");

  /* Display value of HashMap */
  System.out.println(" Elements in HashMap : \n" + mapObj);

  System.out.println("\n Display Values Using keySet");
  Set keySetObj = mapObj.keySet();
  for (Integer intObj : keySetObj) {
   System.out.println("Key :" + intObj + " Value -->"
     + mapObj.get(intObj));

  System.out.println("\n Display Values Using Map.Entry");
  Set<Map.Entry<Integer, String>> entrySet 
= mapObj.entrySet();
  for (Entry e : entrySet) {
   System.out.println("key: " + e.getKey() + 
                           " value --> "+ e.getValue());


Recent Posts