Scala中String的List中的groupBy元素

时间:2017-05-25 20:52:39

标签: scala

我想以正确的方式使用纯FP风格。

如何在Scala中执行此操作?

case class Notes(title: String, body: String, tags: List[String])

val notesList: List[Notes] = retrieveNotesList() // it works

多个音符可以包含相同的标签。

现在我想按标签分组。我无法通过标记完成代码分组注释:

val notesGroupedByTag: Map[String, List[Notes]] = notesList.groupBy {
   case note: Notes => note.tags
}.[_to be completed_]

2 个答案:

答案 0 :(得分:1)

notesList.flatMap(n => n.tags.map(t => (t, n))) // List[(tag, note)]
         .groupBy(_._1)                         // Map[tag, List[(tag, note)]
         .mapValues(_.map(_._2))                // Map[tag, List[note]]

答案 1 :(得分:0)

一种方法是考虑中间List[Tag, Notes]

// Things are a bit more clear with type aliases...
type Title = String
type Tag   = String

case class Notes(title: Title, body: String, tags: List[Tag])

val notes: List[Notes] = retrieveNotesList()

val tagedTitle: List[(Tag, Notes)] =
  notes.flatMap(n => n.tags.map(_ -> n))

val notesGroupedByTag: Map[Tag, List[Notes]] =
  tagedTitle.groupBy(_._1).mapValues(_.map(_._2))