Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Many to Many Collection in Java using Generics (Domain Model, not Persistence Layer)?

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?

like image 848
Daniel Bower Avatar asked Jan 23 '09 17:01

Daniel Bower


1 Answers

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.

like image 199
Paul Brinkley Avatar answered Oct 02 '22 13:10

Paul Brinkley