Saturday, July 14, 2012

ConcurrentHashMap and MultiValueMap - a Map with multiple values per key

a ConcurrentHashMap can only associate 1 value to 1 key:

map.put("a", "bla");
map.put("a", "blu");
map.get("a") will return only "blu".

If I want map.get("a") to return ("bla", "blu") I must use a MultiValueMap to decorate a ConcurrentHashMap

or you can use a Google Collections (Guava) Multimap such as a ArrayListMultimap


Otherwise, if like me you like brewing your own framework, you can decorate yourself a ConcurrentHashmap:


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.xmlbeans.XmlObject;

public class ArrayListMultimap {

 private ConcurrentHashMap<String, List> theMap = new ConcurrentHashMap<String, List<XmlObject>>();
 
 public static ArrayListMultimap create(int i, int j) {
  return new ArrayListMultimap();
 }
 
 public List<XmlObject> put(String key, XmlObject value) {
  List<XmlObject> previousvalue = (List<XmlObject>)theMap.get(key);
  if (previousvalue == null) {
   previousvalue = new ArrayList<XmlObject>();
   previousvalue.add(value);
   theMap.put(key, previousvalue);
  }
  return previousvalue;
 }

 public int size() {
  return theMap.size();
 }

}



No comments: