I am looking for a way to store key-value pairs. I need the lookup to be bidirectional, but at the same time I need to store multiple values for the same key. In other words, something like a BidiMap, but for every key there can be multiple values. For example, it needs to be able to hold pairs like: “s1”->1, “s2”->1, “s3”->2, and I need to be able to get the value mapped to each key, and for each value, get all the keys associated with it.
Share
So you need support for many-to-many relationships? Closest you can get is Guava‘s
Multimaplike @Mechkov wrote – but more specificallyMultimapcombination withMultimaps.invertFrom. “BiMultimap” isn’t implemented yet, but there is an issue requesting this feature in Google Guava library.At this point you have few options:
If your “BiMultimap” is going to immutable constant – use
Multimaps.invertFromandImmutableMultimap/ImmutableListMultimap/ImmutableSetMultimap(each of theese three has different collection storing values). Some code (example taken from app I develop, usesEnums andSets.immutableEnumSet):If you really want your Multimap to be modifiable, it will be hard to maintain both K->V and V->K variants unless you will be modifying only
kToVMultimapand callinvertFromeach time you want to have its inverted copy (and making that copy unmodifiable to make sure that you accidentally don’t modifyvToKMultimapwhat wouldn’t updatekToVMultimap). This is not optimal but should do in this case.(Not your case probably, mentioned as bonus):
BiMapinterface and implementing classes has.inverse()method which givesBiMap<V, K>view fromBiMap<K, V>and itself afterbiMap.inverse().inverse(). If this issue I mentioned before is done, it will probably have something similar.(EDIT October 2016) You can also use new graph API which will be present in Guava 20: