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)
)
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With