问题
I have class CatalogProduct(id: String, name: String)
to declare a product
I have two list below:
val newestCatalogProductList = mutableListOf<CatalogProduct>()
newestCatalogProductList.add(CatalogProduct("A1", "Apple"))
newestCatalogProductList.add(CatalogProduct("A2", "Banana"))
newestCatalogProductList.add(CatalogProduct("A3", "Orange"))
newestCatalogProductList.add(CatalogProduct("A4", "Pineapple"))
val popularCatalogProductList = mutableListOf<CatalogProduct>()
popularCatalogProductList.add(CatalogProduct("A5", "Milk"))
popularCatalogProductList.add(CatalogProduct("A6", "Sugar"))
popularCatalogProductList.add(CatalogProduct("A7", "Salt"))
popularCatalogProductList.add(CatalogProduct("A8", "Sand"))
I merged two list successfully by code below:
newestCatalogProductList.union(popularCatalogProductList)
But, i can not ordering interleaved merged list as expect:
CatalogProduct("A1", "Apple")
CatalogProduct("A5", "Milk")
CatalogProduct("A2", "Banana")
CatalogProduct("A6", "Sugar")
CatalogProduct("A3", "Orange")
CatalogProduct("A7", "Salt")
CatalogProduct("A4", "Pineapple")
CatalogProduct("A8", "Sand")
I'm begin study Kotlin. Please help me if you can explain or make example or give me reference link. So I thank you.
回答1:
You can zip the lists to pair up items with the same index as lists of two items, and then flatten them:
val interleaved = newestCatalogProductList.zip(popularCatalogProductList) { a, b -> listOf(a, b) }
.flatten()
If one of the lists might be longer you probably want to keep the remaining items of the longer list. In that case you might manually zip the items this way:
val interleaved2 = mutableListOf<CatalogProduct>()
val first = newestCatalogProductList.iterator()
val second = popularCatalogProductList.iterator()
while (interleaved2.size < newestCatalogProductList.size + popularCatalogProductList.size){
if (first.hasNext()) interleaved2.add(first.next())
if (second.hasNext()) interleaved2.add(second.next())
}
来源:https://stackoverflow.com/questions/59000336/kotlin-merge-multiple-lists-then-ordering-interleaved-merge-list