如何在 Kotlin 中对 Pair 中的 Flatmap 集合

How to Flatmap collection inside Pair in Kotlin

在这个例子中,我必须 类。

Order(selections: List<Selection>, discount: Double, ...)
Selection(productId: Long, price: Double, ...)

然后我保留 Order 的集合,我想在之后计算价格,需要使用 Selection's priceOrder's discount。我该怎么做?

我尝试执行以下操作,但似乎不可能。

val orderList: List<Order> = loadFromDB()

orderList.map { Pair(it.selections, it.discount) }  
.flatMap { /* Here I want to get list of Pair of selection from all orders with discount. */}

一旦我有了 Pair(Selection, discount) 的集合,我就可以继续进一步计算了。 可以用这种形式吗?需要分链吗?

要获取配对列表,您可以执行以下操作:

orderList.flatMap { order -> //flatMap joins multiple lists together into one
    order.selections.map { selection ->    //Map every selection into a Pair<Selection, Discount>
        Pair(selection, order.discount) }
    .map { pair -> /* Do your stuff here */ }

@D3xter 使用更多 Kotlin 糖的替代语法:

1    orderList
2        .flatMap { order ->
3            order.selections.map { selection ->
4                order.discount to selection.price } 
5        .map { (discount, price) -> ... }

这利用了两个 Kotlin 特性:

  1. to 第 4 行的中缀运算符,它是 Pair
  2. 的 "factory function"
  3. Destructuring 将第 5 行上的对直接放入命名变量 discountprice