Kotlin: Merge Multiple Lists then ordering Interleaved merge list

 ̄綄美尐妖づ 提交于 2021-02-10 18:31:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!