List Kotlin:合并多个列表,然后对交错合并列表排序

List Kotlin:合并多个列表,然后对交错合并列表排序,list,sorting,kotlin,interleave,List,Sorting,Kotlin,Interleave,我有classCatalogProduct(id:String,name:String)来声明产品 我有两个清单: val newestCatalogProductList = mutableListOf<CatalogProduct>() newestCatalogProductList.add(CatalogProduct("A1", "Apple")) newestCatalogProductList.add(CatalogProduct("A2", "Banana")) ne

我有class
CatalogProduct(id:String,name:String)
来声明产品

我有两个清单:

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"))
但是,我不能像预期的那样订购交错合并列表:

CatalogProduct("A1", "Apple")
CatalogProduct("A5", "Milk")
CatalogProduct("A2", "Banana")
CatalogProduct("A6", "Sugar")
CatalogProduct("A3", "Orange")
CatalogProduct("A7", "Salt")
CatalogProduct("A4", "Pineapple")
CatalogProduct("A8", "Sand")

我要开始学习科特林。请帮助我,如果你能解释或举例或给我参考链接。因此,我感谢您。

您可以压缩列表,将索引与两个项目列表相同的项目配对,然后将它们展平:

val interleaved = newestCatalogProductList.zip(popularCatalogProductList) { a, b -> listOf(a, b) }
    .flatten()
如果其中一个列表可能较长,您可能希望保留较长列表中的其余项目。在这种情况下,您可以通过以下方式手动压缩项目:

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())
}
val interleaved2=mutableListOf()
val first=newestCatalogProductList.iterator()
val second=popularCatalogProductList.iterator()
while(interleaved2.size
创建一个新的空可变列表。从0循环到列表的大小(假设它们的大小相同)。对于每个索引,将该索引处两个列表中的元素添加到新列表中。我理解,非常感谢Tenfour04。你是我的英雄。谢谢师父。
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())
}