A basic Java class that allows storage of multiple values per key. It uses a HashMap on top of a List to dictate the organization of the data.

Usage

Here is an example usage:

MultiMap<Integer, String> map = new MultiMap<Integer, String>();
map.add(3, "foo");
map.add(4, "bar");
map.add(4, "baz");
// 'map' now contains:
//    3: foo
//    4: bar, baz
map.remove(3);
// 'map' now contains:
//    4: bar, baz
map.put(4, "foobar");
// 'map' now contains:
//    4: foobar
map.clear(); // Empties the map

Code

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MultiMap<K, V> {
    private Map<K, List<V>> mLocalMap = new HashMap<K, List<V>>();

    public void add(K key, V val) {
        if (mLocalMap.containsKey(key)) {
            List<V> list = mLocalMap.get(key);
            if (list != null)
                list.add(val);
        } else {
            List<V> list = new ArrayList<V>();
            list.add(val);
            mLocalMap.put(key, list);
        }
    }
    public List<V> get(K key) {
        return mLocalMap.get(key);
    }
    public V get(K key, int index) {
        return mLocalMap.get(key).get(index);
    }
    public void put(K key, V val) {
        remove(key);
        add(key, val);
    }
    public void remove(K key) {
        mLocalMap.remove(key);
    }
    public void clear() {
        mLocalMap.clear();
    }
    public String toString() {
        StringBuffer str = new StringBuffer();
        for (K key : mLocalMap.keySet()) {
            str.append("[ ");
            str.append(key);
            str.append(" : ");
            str.append(java.util.Arrays.toString(mLocalMap.get(key).toArray()));
            str.append(" ]");
        }
        return str.toString();
    }
    public Iterable<K> keySet() {
        return mLocalMap.keySet();
    }
    public Set<Entry<K,List<V>>> entrySet() {
        return mLocalMap.entrySet();
    }
}

Next Post Previous Post