Scala:如何从含指定key的Transactions所属Documents中获取reference?
筛选包含特定Transaction的Documents对象或其reference属性
你有以下Scala case class定义:
case class Documents( reference: String, amount: BigDecimal, date: LocalDate, transactions: Seq[Transactions] ) case class Transactions( key: String, date: LocalDate, secret: String )
需要从Seq[Documents]中筛选出其transactions序列包含指定key的Transaction的Documents对象,或者直接获取这些对象的reference属性。当前使用documents.flatMap(_.transactions).find(_.key == argumentPassed)只能得到匹配的Transaction实例,无法满足需求。
1. 筛选匹配的Documents对象
使用filter方法可以得到所有符合条件的Documents:
val targetKey = "your-target-key" // 替换为你要查找的key val matchingDocuments: Seq[Documents] = documents.filter(doc => doc.transactions.exists(_.key == targetKey) )
如果只需要第一个匹配的Documents对象,用find替代filter(返回Option[Documents],避免空指针问题):
val firstMatchingDocument: Option[Documents] = documents.find(doc => doc.transactions.exists(_.key == targetKey) )
2. 获取匹配Documents的reference属性
在筛选后直接提取reference即可:
val matchingReferences: Seq[String] = documents .filter(doc => doc.transactions.exists(_.key == targetKey)) .map(_.reference)
同样,若只需要第一个匹配的reference:
val firstMatchingReference: Option[String] = documents .find(doc => doc.transactions.exists(_.key == targetKey)) .map(_.reference)
内容的提问来源于stack exchange,提问作者laban_luka
相关产品推荐
相关产品推荐

