javadata-structures

Implementing a one to many map in Java


Have one object of type A that is related to a bunch of objects of type B and want to store all objects of type A and easily access their type B relations.

What's the best (built-in?) data structure doing this in Java?


Solution

  • You could have a Map of type A objects to a List or Set (or whichever Collection works best) of type B objects, like:

     Map<A,List<B>> map = new HashMap<A,List<B>>();
    

    Or use Google's Multimap interface, which will do essentially the same as above, but with less work on your part.