Data structure for representing many, many relationships

If we have a Student and Course essence, and the relationship between them is a lot for many. A student can take many courses, and the course can be accepted by many students. If we are to present this relationship, then what is the best data structure through which we can present this relationship. If we use a hashmap with a student as the key and a list of courses that the student took for value, we need another hash file through which we can present the course to student relations. Are there any better ways to represent this relationship so that the search is quick.

+7
java collections data-structures
source share
2 answers

A bidirectional graph can be used to implement many-to-many relationships, where each node can be connected to many other nodes

+1
source share

I find it appropriate to use a combination of data structures. Here is a small example:

public class ManyToManyMap<S, C> { private Map<S, Set<C>> firstToSecondMap = new HashMap<>(); private Map<C, Set<S>> secondToFirstMap = new HashMap<>(); public void put(S first, C second) { if (!firstToSecondMap.containsKey(first)) { firstToSecondMap.put(first, new HashSet<>()); } firstToSecondMap.get(first).add(second); if (!secondToFirstMap.containsKey(second)) { secondToFirstMap.put(second, new HashSet<>()); } secondToFirstMap.get(second).add(first); } public Set<C> getFirst(S first) { return firstToSecondMap.get(first); } public Set<S> getSecond(C second) { return secondToFirstMap.get(second); } public Set<C> removeByFirst(S first) { Set<C> itemsToRemove = firstToSecondMap.remove(first); for (C item : itemsToRemove) { secondToFirstMap.get(item).remove(first); } return itemsToRemove; } public Set<S> removeBySecond(C second) { Set<S> itemsToRemove = secondToFirstMap.remove(second); for (S item : itemsToRemove) { firstToSecondMap.get(item).remove(second); } return itemsToRemove; } } 

And here is a usage example:

 ManyToManyMap<String, String> mmMap = new ManyToManyMap<>(); mmMap.put("Tom", "Math"); mmMap.put("Tom", "Java"); mmMap.put("Tom", "Java"); mmMap.put("Mary", "Java"); Set<String> coursesByStudent = mmMap.getFirst("Tom"); // Java, Math Set<String> studentByCourse = mmMap.getSecond("Java"); // Tom, Mary mmMap.removeByFirst("Tom"); studentByCourse = mmMap.getSecond("Java"); // Mary 
0
source share

All Articles