Adam_G
Adam_G

Reputation: 7879

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?

Upvotes: 5

Views: 704

Answers (3)

Nayuki
Nayuki

Reputation: 18542

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.

Upvotes: 4

Andy Guibert
Andy Guibert

Reputation: 42936

Just use 2 hahsmaps. Lets say your "one" is of type Integer and "many" is of type String for simplicity.

HashMap<Integer, String> intToString = new HashMap<>();
HashMap<String, HashSet<Integer>> stringToInt= new HashMap<>();

funciton for linking elements:

public void linkElements(Integer i, String s){
  intToString.add(i,s);
  stringToInt.get(s).add(i);
}

getting values would be like this:

intToString.get(0);    // returns "a"
stringToInt.get("b");  // returns a set {1,2,3}

Upvotes: 1

Alaa Abuzaghleh
Alaa Abuzaghleh

Reputation: 1009

yes use JPA(Java Persistence API) it will give you the ability to make @OneToMany and in the child it will give you List with @ManyToOne basically it will be reference to property to your patent property. Example

public class Table1{
    @Id 
    int id ; 
    @OneToMany 
    List<Table2> ls ; 

   // getter and setter ...
}

public class Table2{
        @Id 
        int id ; 
        @ManyToOne 
        Table1 t1 ; 

       // getter and setter ...
    }

hopefully this help you

Upvotes: -1

Related Questions