Wednesday, March 20, 2013

Java HashMap Example

Java HashMap Example :

HashMap is the class in java.util package, The main advantage of HashMap is to store the information in the form of Key/Value pairs. In this HashMap Object we can store the null values also. that means the HashMap accepts to store the null values as key/value pairs. Suppose you are retrieving the data from the database, if some records are returned with null values. you can store these null values also in this HashMap object.

HashMap is not synchronized.


Below is the very straight and quick start example for HashMap.

The below HashMap example stores key/value pairs and just retrieve from the HashMap again and printing the key/value data.


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

public class HashMapExample {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        @SuppressWarnings("rawtypes")
        HashMap map = new HashMap();
        // add the elements to the hashmap
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        map.put("key4", null);
        @SuppressWarnings("rawtypes")
        Set set = map.entrySet();
        @SuppressWarnings("rawtypes")
        Iterator iterator = set.iterator();
        // Iterate teh elements from the hashmap
        while (iterator.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry keyValue = (Map.Entry) iterator.next();
            System.out.println("key....." + keyValue.getKey() + " value...."
                    + keyValue.getValue());
        }

    }

}



Output :

key.....key4 value....null
key.....key3 value....value3
key.....key2 value....value2
key.....key1 value....value1





0 comments:

Post a Comment

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.