2017-06-02 37 views
0

在這個例子中,我不得不上課。如何在Kotlin中對Pair內收集

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)收集,那麼我可以繼續進一步計算。 這樣做有可能嗎?我需要分開鏈嗎?

回答

6

爲了得到對的列表,你可以做到以下幾點:

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 */ } 
+0

好像我真的沒有想到不夠大。謝謝。 – RobGThai