按类列表过滤scala case类列表?

时间:2018-10-18 22:36:53

标签: scala

我在Scala中有以下case class

case class Profile(userId: String, items: Map[String, Seq[Item]], subParts: Seq[SubPartAndCount], usedItems: Map[String, Long])

SubPartandCount看起来像这样:

case class SubPartAndCount(subPart: String, subCount: Int)

因此,我想通过Profile s列表中的subPart案例类中的SubPartAndCount的值来过滤subPart的列表。我一直试图解决这个问题,但没有成功!任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

使用.exists(A => Boolean)中嵌套的.filter(B => Boolean)

profileList.filter(_.subParts.exists(_.subPart == "Part A"))

这里是一个例子:

type Item = String

case class Profile(userId: String, items: Map[String, Seq[Item]], subParts: Seq[SubPartAndCount], usedItems: Map[String, Long])

case class SubPartAndCount(subPart: String, subCount: Int)

val subPartA = SubPartAndCount("Part A", 100)
val subPartB = SubPartAndCount("Part B", 200)

val exampleItems = Map("Hello" -> Seq("World", "Galaxy", "Universe"))
val exampleUsedItems = Map("Hello" -> 1L, "Goodbye" -> 2L)

val profileList = Seq(
  Profile("good", exampleItems, Seq(subPartA, subPartB), exampleUsedItems),
  Profile("bad", exampleItems, Seq(subPartB, subPartB), exampleUsedItems),
  Profile("good", exampleItems, Seq(subPartB, subPartA), exampleUsedItems)
)

profileList.filter(_.subParts.exists(_.subPart == "Part A"))

Try it out!

此语句的计算结果为两个“好” Seq中的Profile

希望这会有所帮助。