Scala:过滤列表和创建未来序列的更有效方法
Scala: More Efficient Way to Filter a List and Create a Sequence of Futures
给定 Order
个对象的列表...
case class Order(val id: String, val orderType: Option[String])
case class Transaction (val id: String, ...)
val orders = List(Order(1, Some("sell")), Order(2, None), ...)
...我需要为所有具有类型(即定义了 orderType
)的订单创建一个 Future
序列:
val transactions: Seq[Future[Transaction]] = orders.filter(
_.orderType.isDefined).map { case order =>
trxService.findTransactions(order.id) // this returns a Future[Transaction]
}
)
上面的代码首先调用 filter
,它创建一个新的 List
,其中仅包含 orderType
设置为 Some
的订单,然后创建一个 Future
s 出来了。有没有更有效的方法来完成这个?
您可以使用 collect
聚合 filter
和 map
val transactions: Seq[Future[Transaction]] = orders.collect {
case order if order.orderType.isDefined => trxService.findTransactions(order.id)
}
给定 Order
个对象的列表...
case class Order(val id: String, val orderType: Option[String])
case class Transaction (val id: String, ...)
val orders = List(Order(1, Some("sell")), Order(2, None), ...)
...我需要为所有具有类型(即定义了 orderType
)的订单创建一个 Future
序列:
val transactions: Seq[Future[Transaction]] = orders.filter(
_.orderType.isDefined).map { case order =>
trxService.findTransactions(order.id) // this returns a Future[Transaction]
}
)
上面的代码首先调用 filter
,它创建一个新的 List
,其中仅包含 orderType
设置为 Some
的订单,然后创建一个 Future
s 出来了。有没有更有效的方法来完成这个?
您可以使用 collect
filter
和 map
val transactions: Seq[Future[Transaction]] = orders.collect {
case order if order.orderType.isDefined => trxService.findTransactions(order.id)
}