I have data in a many-to-one relationship. I'd like to be able to lookup data from both directions. An example:
0 : a
1 : b
2 : b
3 : b
4 : c
get(0) --> a
get(1) --> b
get(a) --> 0
get(b) --> (1:3)
Does this make sense? Is it possible?
It is definitely possible. Here is a fragment of code for adding items:
Map<Integer,String> forwardMap = new HashMap<>();
Map<String,Set<Integer>> reverseMap = new HashMap<>();
void add(Integer x, String y) {
forwardMap.put(x, y);
if (!reverseMap.containsKey(y))
reverseMap.put(y, new HashSet<Integer>());
reverseMap.get(y).add(x);
}
Footnote: Apache Commons has BidiMap and Google Guava has BiMap, but these appear to be one-to-one maps, disallowing the many-to-one case asked in the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With