如何在 kotlin 中组合两个不同长度的列表? [英] How to combine two different length lists in kotlin?

查看:40
本文介绍了如何在 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屋!

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