如何在Kotlin中并行迭代两个列表? [英] How to iterate two list in parallel in Kotlin?

查看:129
本文介绍了如何在Kotlin中并行迭代两个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Kotlin中迭代两个列表?我想将一个列表中的每个值分配给另一列表中的等效textview,例如1:1分配.

How do I iterate two lists in Kotlin? I want to assign each value in one list to the equivalent textview in another list, like 1 : 1 assignment.

类似于以下的内容允许并行迭代,但它会执行两次:

Something like the following allows parallel iteration but it gets executed twice:

data class Total(val area : Double)

private fun assign(
    allArea: List<Double>, allTextViews : List<TextView>
) : Total {
    var totalArea = 0.0

    allArea.forEach { double ->
        val value : Double = double
        totalArea += value

        allTextViews.forEach { textView ->
            textView.text = value.toString()
        }
    }
    return Total(totalArea)
}

assign(allStates = listOf(
        a,
        b
    ),
    allTextViews = listOf(
        textView1,
        textView2)
)

推荐答案

尝试压缩两个列表:

fun main() {
    val list1 = listOf(1,2,3)
    val list2 = listOf(4,5,6)
    list1.zip(list2).forEach {pair -> 
       println(pair.component1() + pair.component2())
    }
}

此打印:

5
7
9

在给定allArea列表和allTextViews具有相同长度的情况下,您可以将它们压缩并获得一对,第一个组件的类型将为Double,第二个组件的类型为

In your case given the allArea list and allTextViews have the same length, you can zip them and get the pair of which the first component will be of type Double, and the second is of type TextView

这篇关于如何在Kotlin中并行迭代两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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