Thursday, March 8, 2012

Java HashMap Example

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.

The following constructors are defined:  
HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)


Hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read.

Here is the code:
import java.util.HashMap;
import java.util.Map;

 * This Java HashMap example describes the basic operations performed on the HashMap
 * @author abdul
public class HashMapExample {
    public static void main(String args[]){
        // constructs a new empty HashMap with default initial capacity       
        Map<Integer,String> hashMap = new HashMap<Integer,String>();
        // adding value into HashMap
        hashMap.put(new Integer(1),"DELL");
        hashMap.put(new Integer(2),"SONY");
        hashMap.put(new Integer(3),"LENOVO");
        hashMap.put(new Integer(4),"SAMSUNG");
        hashMap.put(new Integer(5),"HP");
        //To get the size of HashMap       
        System.out.println("HashMap Size: " + hashMap.size());
        // To Find particular value from the HashMap:
            System.out.println("HashMap contains HP");
            System.out.println("HashMap does not contain HP");
        //To find particular key in HashMap
        if( hashMap.containsKey(new Integer(2)) ){
            System.out.println("HashMap contains key");
            System.out.println("HashMap does not contain key");
        Use get method of HashMap to get value mapped to particular key.       
        Signature of the get method is,       
        Object get(Object key)       
        String value = hashMap.get(new Integer(5));       
        System.out.println("Value : " + value);

        //To get the key value pair of hashMap
        for (Map.Entry<Integer, String> entry1 : hashMap.entrySet()) {
            Integer key = entry1.getKey();
            String data = entry1.getValue();
            System.out.println("key value : " + key + "\t" + data );

        // To remove something from the hashmap      
        System.out.println( hashMap.remove(new Integer(4)) + " removed from the hashMap");
        //Display value of HashMap
        System.out.println("HashMap : " + hashMap );

HashMap Size: 5
HashMap contains HP
HashMap contains key
Value : HP
key value : 1    DELL
key value : 2    SONY
key value : 3    LENOVO
key value : 4    SAMSUNG
key value : 5    HP
SAMSUNG removed from the hashMap
HashMap : {1=DELL, 2=SONY, 3=LENOVO, 5=HP}