如何在Kotlin中创建对内的Flatmap集合
在这个例子中,我必须学习两个类如何在Kotlin中创建对内的Flatmap集合,kotlin,higher-order-functions,flatmap,Kotlin,Higher Order Functions,Flatmap,在这个例子中,我必须学习两个类 Order(selections: List<Selection>, discount: Double, ...) Selection(productId: Long, price: Double, ...) 一旦我收集了对(选择、折扣),我就可以继续进一步计算了。 在这种形式下可以这样做吗?是否需要分离链?要获得对的列表,可以执行以下操作: orderList.flatMap { order -> //flatMap joins multip
Order(selections: List<Selection>, discount: Double, ...)
Selection(productId: Long, price: Double, ...)
一旦我收集了对(选择、折扣)
,我就可以继续进一步计算了。
在这种形式下可以这样做吗?是否需要分离链?要获得对的列表,可以执行以下操作:
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 */ }
orderList.flatMap{order->//flatMap将多个列表合并为一个
order.selections.map{selection->//将每个选择映射为一对
配对(选择、订购、折扣)}
.map{pair->/*在这里做你的事*/}
对于@D3xter的答案,另一种语法是使用更多的Kotlin sugar:
1 orderList
2 .flatMap { order ->
3 order.selections.map { selection ->
4 order.discount to selection.price }
5 .map { (discount, price) -> ... }
这利用了Kotlin的两个功能:
对的“工厂函数”
折扣
和价格
看起来我真的没有考虑太多。谢谢。
1 orderList
2 .flatMap { order ->
3 order.selections.map { selection ->
4 order.discount to selection.price }
5 .map { (discount, price) -> ... }