如何在Kotlin中组合两个不同的长度列表? [英] How to combine two different length lists in kotlin?
本文介绍了如何在Kotlin中组合两个不同的长度列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想组合两个不同的长度列表.例如;
I want to combine two different length lists. For example;
val list1 = listOf(1,2,3,4,5)
val list2 = listOf("a","b","c")
我想要这样的结果
(1,"a",2,"b",3,"c",4,5)
有什么建议吗?
推荐答案
您可以为此使用.zip
函数
list1.zip(list2){ a,b -> listOf(a,b)}.flatten()
唯一的问题是,它将只处理带有两个集合的元素,因此,如果(如示例中)让我们具有不同的大小-它将无法工作
The only problem is that it will only process elements, with both sets, so if (like in the example) let's have different size - it will not work
另一种选择是添加特定标记并对其进行过滤,或者仅使用迭代器.我找到了sequence{..}
函数
The alternative could be to add specific markers and filter them or to just use iterators for that. I found an elegant solution with sequence{..}
function
val result = sequence {
val first = list1.iterator()
val second = list2.iterator()
while (first.hasNext() && second.hasNext()) {
yield(first.next())
yield(second.next())
}
yieldAll(first)
yieldAll(second)
}.toList()
这篇关于如何在Kotlin中组合两个不同的长度列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文