Pacific-Design.com

    
Home Index

1. Algorithms

2. Hash Map

+ Nested

Algorithms / Hash Map /

HashMap

package testmap;
import java.util.Map;
import java.util.HashMap;

/*------------------------------------------------------------------------------ 
 * HashMap: Hash table based implementation of the Map interface 
 * and permits null values and the null key. 
 * Keys are stored in the un sorted order. 
 */
public class TestHashMap {

    /*------------------------------------------------------------------------*/
    public static void main(String[] args) {
        TestHashMap test = new TestHashMap();
        Map<String, String> map = test.PopulateHashMap();
        test.DisplayHashMap(map);
    }

    /*------------------------------------------------------------------------*/
    public Map<String, String> PopulateHashMap() {
        Map<String, String> map = new HashMap();
        map.put("key1", "value1");
        map.put("key3", "value3");
        map.put("key5", "value5");
        map.put("key6", "value6");
        map.put("key7", "value7");
        map.put("key4", "value4");
        map.put("key2", "value2");        
        return map;
    }
    /*------------------------------------------------------------------------*/

    public void DisplayHashMap(Map<String, String> map) {

        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " => " + value);
        }
    }
    /*------------------------------------------------------------------------*/

    public void IterateHashMap(Map map) {

        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            System.out.println(pairs.getKey() + " = " + pairs.getValue());
            it.remove(); // avoids a ConcurrentModificationException
        }
    }    
    /*------------------------------------------------------------------------*/
}
/*
key4 => value4
key3 => value3
key6 => value6
key5 => value5
key2 => value2
key1 => value1
key7 => value7
 */