Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

scala: union of two maps whose key type is the same and whose value type is a collection of elements, but whose types are different

I would like to create a union of two maps whose key type is the same and whose value type is a collection of elements, but whose types are different.

Consider the following contrived example:

case class Child(name: String)
val peopleToChildren: Map[String, Seq[Child]] = 
  Map("max" -> Seq(Child("a"), Child("b")), 
    "yaneeve" -> Seq(Child("y"), Child("d")))

case class Pet(name: String)
val peopleToPets: Map[String, Seq[Pet]] = 
  Map("max" -> Seq(Pet("fifi")), 
    "jill" -> Seq(Pet("bobo"), Pet("jack"), Pet("Roger rabbit")))

val peopleToChildrenAndDogs: Map[String, (Seq[Child], Seq[Pet])] = {
  // people may have children
  // people may have pets
  // would like a map from people to a tuple with a potentially empty list of children and a
  //     potentially empty list of pets
  // ???
}

What would be a way to do it which is concise, idiomatic, but still legible?

I found no single function that can do that in the standard scala collections library.

Proposed solutions can be based solely on the standard library, or propose an external solution.

I post it here since I could not easily find an online solution to a seemingly standard operation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This appears to work.

val peopleToChildrenAndDogs: Map[String, (Seq[Child], Seq[Pet])] = {
  (peopleToChildren.keySet ++ peopleToPets.keySet).map { k =>
    k -> (peopleToChildren.getOrElse(k, Seq())
         ,peopleToPets.getOrElse(k, Seq()))
  }.toMap
}

Get all the keys. For every key do a getOrElse() on each of the feeder Maps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...