I'm using Apache commons collection for quite some time. For those who doesn't use it yet, here is a link to the project : http://commons.apache.org/collections/. Basically, it make it easier to manipulate collections within Java from filtering, transforming, sorting ,etc. It also provide new kind of data structure: BidiMap and MultiMap. But, did you notice there wasn't a BidiMultiMap. i.e. a data structure to represent a many-to-many relation type. When I need it, I just waste time creating two maps Map<A, Set<B>> and Map<B, Set<A>>. and write many lines to maintain both collection.

I've spent the last day writing an implementation of BidiMultiMap backed by three hash table. It doesn't depend on Apache common collection. {% highlight java %} BidiMultiMap map = new BidiMultiHashMap(); map.put("a", "1"); map.put("a", "2"); map.put("a", "3"); map.put("b", "1"); map.put("b", "2"); int size = map.size(); Set keys = mhm.keySet(); Set values = mhm.valueSet(); size will be 5. keys will be a set containing "a", "b". values will be a set containing "1", "2", "3".

You may get the full source code from this location.

Edit Nov 18, 2012: I change the implementation to support null key and null value. I add a license notice in each file.

Edit Apr 1, 2013: I fix a performance issue when using BidiMultiHashMap.

Category: java • 2012-09-11
Share this post