I am not sure what data structure I should use to solve it,
I have a list of categories and list of values that are associated to them as following:
Categories Values
Smart **person1**,person2
Handsome person3,person6,**person1**
Hard-Working person7,person9
For example, person1 is Smart and Handsome because he is in both Handsome and Smart categories. (a value(person) can be in many categories) and person2 is Smart but is not Handsome.
person object has name,age and gender for example person 1 is
John 43 Male
I am wondering how I can design it, I was thinking of a two-dimention array but it is not a good idea as I would have some spare places
Cat1 v3,v6 Spare Spare
Cat2 v10 Spare Spare Spare
cat4 v6,v7,v8,v9
I suppose the best is to have a list but not sure how to find out which value is for which category or categories ( like V6 in above example that is associated to both cat1 and cat4)
V3 v6 v7 v8 v9 v10
You could use something like
Map<Category, List<Person>>Since
Mapshould provide O(1) access, you want your key to be what you use to look up the most (Category in your case, from what I gather). So if you haveMap<Category, List<Person>> categoryLookup = new HashMap<Category, ArrayList<Person>>();you can do
List<Person> values = myCategoryLookup.get(someCategory);and then iterate over the values. References to the same value can be in multiple lists — that is not a problem.
For Yameo below, if you want to get categories for a person, you can either
Personmaintain a list of its categoriesMap<Person, List<Category>>The alternative to these solutions is to set the relationships in the
CategoryandPersonclasses themselves. For example,Personwould have aList<Category>as one of its class properties, and similarlyCategorywould have aList<Person>as one of its class properties. But I get the sense this is more a data-structures question. This what you would probably do if you had a database that contains the actual data and were going to use an ORM tool to map the data to Java classes.