Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Many-to-one bidirectional lookup

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?

like image 273
Adam_G Avatar asked Sep 29 '22 02:09

Adam_G


1 Answers

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.

like image 75
Nayuki Avatar answered Oct 31 '22 19:10

Nayuki