HashMap implements Map

HashMap implements Map:-
 
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.
The two most important HashMap's methods are:
- get( Object key ) - returns the value associated with specified key in this hash map, or null if there is no value for this key
- put(K key, V value) - associates the specified value with the specified key in this map
There are some other useful HashMap's methods:
- containsKey(Object key) - (boolean) returns true if this map contains a value for the specified key
- values() - returns a collection of the values contained in this map
- keySet() - returns a set view of the keys contained in this map
- remove(Object key) - removes the mapping for key from this map if present
- isEmpty() - (boolean) returns true if this map contains no key-value mappings
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

People who read this post also read :



0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More