将列表List [String,String]转换为Scala中的List [String,List [String]]?

时间:2012-06-11 19:29:48

标签: scala functional-programming

我想列出一个RawDoc列表,每个列表都有一个title和一个version,然后将其转换为Doc列表,每个列表都有一个title {1}}及其所有versions一起收集到一个列表中:

case class RawDoc(title:String, version:String)
case class Doc(title:String, versions:List[String])

val rawDocs:List[RawDoc] = List(
  RawDoc("Green Book", "1.1"),
  RawDoc("Blue Book",  "1.0"),
  RawDoc("Green Book", "1"),
  RawDoc("Blue Book",  "2")
)

我想从上面的rawDocs开始,然后像这样创建docs

val docs:List[Doc] = List(
  Doc("Green Book", List("1.1", "1")),
  Doc("Blue Book",  List("1.0", "2"))
)

不使用for循环如何在Scala中完成?

2 个答案:

答案 0 :(得分:5)

这应该有效:

val docs = rawDocs.
  groupBy(_.title).map{
    case(title, docsWithSameTitle) => 
      Doc(title, docsWithSameTitle.map(_.version))
  }

如果"Blue Book""Blue BooK"之间的差异不是偶然的拼写错误,那么它们应该被视为平等:

val docs = rawDocs.
  groupBy(_.title.toUpperCase).map{
    case(_, docsWithSameTitle) => 
      Doc(docsWithSameTitle.head.title, docsWithSameTitle.map(_.version))
  }

答案 1 :(得分:4)

rawDocs.groupBy(_.title).mapValues(_ map (_.version)).map { 
  case (title, versions) => Doc(title, versions) 
}