我在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
的列表。我一直试图解决这个问题,但没有成功!任何帮助将不胜感激!
答案 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"))
此语句的计算结果为两个“好” Seq
中的Profile
。
希望这会有所帮助。