Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate two list in parallel in Kotlin?

Tags:

list

kotlin

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)
)
like image 638
Kellin Strook Avatar asked Apr 27 '20 05:04

Kellin Strook


People also ask

How to iterate two list simultaneously in Kotlin?

One way is to use zip operator them making a pair but make sure they equal sizes. you can then have transformation inside the lambda function or take it as list and then iterate over it.

How do I use a list on Kotlin?

Inside main() , create a variable called numbers of type List<Int> because this will contain a read-only list of integers. Create a new List using the Kotlin standard library function listOf() , and pass in the elements of the list as arguments separated by commas.


1 Answers

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

like image 188
Mark Bramnik Avatar answered Oct 07 '22 06:10

Mark Bramnik