Pacific-Design.com

    
Home Index

1. Algorithms

2. Linked Hash Map

+ Nested

Algorithms / Linked Hash Map /

LinkedHashMap

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

/*------------------------------------------------------------------------------ 
 * LinkedHashMap: Hash table and linked list implementation of the Map 
 * interface, with predictable iteration order. 
 * Keys are stored in the order they were inserted.
 */
public class TestLinkedHashMap {

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

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

     
        return map;
    }
    /*------------------------------------------------------------------------*/

    public void DisplayLinkedHashMap(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 IterateLinkedHashMap(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
        }
    }    
    /*------------------------------------------------------------------------*/
}
/*
 * key1 => value1
 * key3 => value3
 * key2 => value2
 * key4 => value4
 * key5 => value5
 * key7 => value7
 * key6 => value6
*/