How to iterate two list in parallel in Kotlin?

限于喜欢 提交于 2021-01-24 10:51:20

问题


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

回答1:


Try to zip two lists:

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

This prints:

5
7
9

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




回答2:


One way is to use zip operator them making a pair but make sure they equal sizes.

fun main() {
    val listA = listOf("A","B","C")
    val listB = listOf(1,2,3)
    val zippedList = listA.zip(listB)
    //or
    val zippedListIterative = listA.zip(listB, {a, b -> "${a} = ${b}"}).toList()
    println(zippedList)
}

you can then have transformation inside the lambda function or take it as list and then iterate over it.



来源:https://stackoverflow.com/questions/61452362/how-to-iterate-two-list-in-parallel-in-kotlin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!