Java – HashMap Example

HashMap class is part of java.util package. HashMap class can add key and value put(key, value) pair elements. This HashMap permits null key and value. But HashMap is unsynchronized. HashMap class gives no guarantee to return as original order as entered.
HashMap extends AbstractMap class and implements Map interface. Key and value of HashMap can get by Set Interface and Map interface through Iterator interface.

HashMap example give a method, how to use HashMap in java.

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

public class HashMapExample {

    public static void main(String[] args) {

        HashMap<Object,String> hm=new HashMap<Object,String>();

        // adding or set elements in HashMap by put method key and value pair
        hm.put(new Integer(2), "Two");
        hm.put(new Integer(1), "One");
        hm.put(new Integer(3), "Three");
        hm.put(new Integer(4), "Four");

        // Get hashmap in Set interface to get key and value
        Set s=hm.entrySet();

        // Move next key and value of HashMap by iterator
        Iterator it=s.iterator();

        while(it.hasNext())
        {
            // key=value separator this by Map.Entry to get key and value
            Map.Entry m =(Map.Entry)it.next();

            // getKey is used to get key of HashMap
            int key=(Integer)m.getKey();

            // getValue is used to get value of key in HashMap
            String value=(String)m.getValue();

            System.out.println("Key :"+key);
            System.out.println("value :"+value);
        }
    }
}

Output

Key :1
value :One
Key :2
value :Two
Key :3
value :Three
Key :4
value :Four

Tags:

Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post