19

I seem to be using the wrong search terms for this in Google...

I have written a Generic Class for Many-To-Many Associations, but I'm guessing this has already been done. It is highly likely that it exists in an implementation much better than my own. This is my first foray into writing a generic class.

For a better idea of what I'm looking for, I am including some snippets of my own:

I've backed it with 2 hashmaps:

private final Map<T, List<S>> ssForTs = new HashMap<T, List<S>>();
private final Map<S, List<T>> tsForSs = new HashMap<S, List<T>>();

Here is the instantiation:

new ManyToManyAssociations<Integer, Integer>();

Some of the methods available:

  • public void addAssociation(T t, S s)
  • public void removeAssociation(T t, S s)
  • public List<T> getListOfTs()
  • public List<S> getListOfSs()
  • public List<T> getTsForSs(S s)
  • public List<S> getSsForTs(T t)

The names of the methods are quite poor... I apologize.

Basic usage is: I can find all S for T and the reverse quite easily.

Can you post the link to a polished library that already includes this functionality?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Daniel Bower
  • 739
  • 1
  • 7
  • 27
  • I've written a few of these myself. I don't believe there is a generic one. – Paul Tomblin Jan 23 '09 at 17:53
  • Is there a question here? If you want to advertise your library, maybe there is a better place to do it? Post it on refactormycode.com, for instance. – Tim Frey Jan 23 '09 at 18:00
  • 4
    no advertising... I just think it is likely that it has been done somewhere else, and better... – Daniel Bower Jan 23 '09 at 18:07
  • I need this type of collection badly. I hope it will be implemented in Google Collections/Guava soon, but it does not look likely. – nimcap Jul 27 '10 at 09:25
  • For anyone that stumbles upon this question, I submitted a feature request to Guava-libraries (AKA Google COllections). Now its up to someone else to create it as I have a headache from doing it myself. http://code.google.com/p/guava-libraries/issues/detail?id=394&start=100 – TheLQ Aug 10 '10 at 21:24
  • Maybe this will help: http://stackoverflow.com/questions/2571652/java-many-to-many-association-map – Erel Segal-Halevi Jul 17 '12 at 13:31

2 Answers2

4

So far, this is a less trivial question than I thought. The two Java Collections extensions I know of off the top of my head are the Google one mentioned by duffymo, and the Apache Commons Collections. Neither has a many-to-many map. In Google's terminology, it would be a BiMultiMap; in Apache's, it would be a BidiMultiMap or MultiBidiMap.

Paul Brinkley
  • 6,283
  • 3
  • 24
  • 33
2

Looks like Apache Commons Multimap might be useful.

EDIT: except it's one-to-many, not many-to-many. However, it still might be handy to use instead of your Map<T, List<S>> and Map<S, List<T>>, or as a reference.

Michael Myers
  • 188,989
  • 46
  • 291
  • 292