Thursday, 2 August 2012

What is HashMap and Map?

      Map is an Interface which is part of Java collections framework. This is used to store Key-Value pairs, and HashMap is the class that implements Map Interface.

      EX:
        package com.ks.j2se;
        import java.util.HashMap;
        import java.util.Iterator;
        import java.util.Map;
        import java.util.Set;
         
        public class HashMapDemo {
        public static void main(String[] args) {
        try {
        Map<String,String> hMap = new HashMap<String,String>();
        hMap.put("Db2" ,"Expensive Enterprise database from IBM");
        hMap.put("Oracle" , "Expensive Enterprise Database from Oracle");
        hMap.put("MySQL" , "Free Open Source Database from Sun Microsystems");

        Iterator itr = hMap.entrySet().iterator(); 
        //getting the keys of hashmap in the form of set, so that we can iterate over keys in loop and in each iteration we can get the corresponding value associated with the key
        while (itr.hasNext()) {
        Map.Entry mEntry = (Map.Entry) itr.next();
        System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
        }
        } catch (Exception e) {
        System.out.println(e.toString());
        }
        }
        }

No comments:

Post a Comment