Pacific-Design.com

    
Home Index

1. Algorithms

2. Tree Map

Algorithms / Tree Map /

TreeMap

package test;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/*------------------------------------------------------------------------------ 
 * TreeMap: Red-Black tree based NavigableMap implementation. 
 * Keys are stored in the sorted order. 
 ----------------------------------------------------------------------------*/
public class KeyValueCount {

    Map<String, Integer> map = new TreeMap();

    /*------------------------------------------------------------------------*/
    public void populateTreeMap() {

        map.put("key1", 3);
        map.put("key3", 2);
        map.put("key5", 5);
        map.put("key3", 1);
        map.put("key5", 7);
        map.put("key4", 2);
        map.put("key2", 6);
        
        /*--------------------------------*/
        incrementValue("key1", 100);
        incrementValue("key3", 100);
        incrementValue("key5", 100);
    }

    /*------------------------------------------------------------------------*/
    public void incrementValue(String key, Integer value) {

        int count = map.containsKey(key) ? map.get(key) : 0;
        count += value;
        map.put(key, count);

    }
    /*------------------------------------------------------------------------*/

    public void displayTreeMap() {

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

    /*------------------------------------------------------------------------*/
    public void iterateTreeMap() {

        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            System.out.println(pairs.getKey() + " = " + pairs.getValue());
            it.remove(); 
        }
    }

    /*------------------------------------------------------------------------*/
}
/*
key1 => 103
key2 => 6
key3 => 101
key4 => 2
key5 => 107
 */