Reputation: 22128
Lets say I have the class Family
which has a structure of members of the family inside it, not really relevant for this problem as long as there is a function provided by Family
called def member(m : Member) : Boolean
which returns true
if the member m
is 'part' of the family.
Most importantly however, a member can be part of multiple families.
I have a separate list of all the Members and wish to create a mapping between member and family for fast lookup.
So I have something like this:
val allMembers : Set[Member] = getAllMembers()
val allFamilies : Set[Family] = getAllFamilies()
val memberFamilyMap : Map[Member, Set[Family]] = ???
What is the most efficient way to create the above memberFamilyMap
given the Family.member
function, and that a member can be a member of multiple families? I am trying to use a for-comprehension with generators of the two, but things got a bit hairy (I am a bit new to Scala)
Upvotes: 2
Views: 49
Reputation: 5768
I would do it like this:
allMembers.map(m => m -> allFamilies.filter(_.member(m))).toMap
There might be something more efficient though.
Upvotes: 5