Kotlin:合并多个列表,然后订购交错的合并列表 [英] Kotlin: Merge Multiple Lists then ordering Interleaved merge list

查看:61
本文介绍了Kotlin:合并多个列表,然后订购交错的合并列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类 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"))

我通过以下代码成功合并了两个列表:

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.

推荐答案

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

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())
}

这篇关于Kotlin:合并多个列表,然后订购交错的合并列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆