0
0
Kotlinprogramming~5 mins

Destructuring in collection iteration in Kotlin

Choose your learning style9 modes available
Introduction
Destructuring helps you easily get parts of each item when you look through a list or map. It makes your code simple and clear.
When you want to get both keys and values from a map while looping.
When you have a list of pairs and want to use each part separately.
When you want to quickly access multiple values inside a loop without extra code.
Syntax
Kotlin
for ((key, value) in map) {
    // use key and value
}

for ((first, second) in listOfPairs) {
    // use first and second
}
You use parentheses to get parts of each item directly.
This works well with pairs or maps where each item has two parts.
Examples
Loop through a map and print each key and value.
Kotlin
val map = mapOf("a" to 1, "b" to 2)
for ((key, value) in map) {
    println("Key: $key, Value: $value")
}
Loop through a list of pairs and print each part.
Kotlin
val list = listOf(Pair("x", 10), Pair("y", 20))
for ((first, second) in list) {
    println("First: $first, Second: $second")
}
Sample Program
This program loops through a map of fruits and their counts, printing each one clearly.
Kotlin
fun main() {
    val map = mapOf("apple" to 3, "banana" to 5)
    for ((fruit, count) in map) {
        println("We have $count $fruit(s)")
    }
}
OutputSuccess
Important Notes
Destructuring works only if the item has component functions like component1(), component2().
You can ignore parts you don't need by using an underscore (_).
This makes your loops cleaner and easier to read.
Summary
Destructuring lets you get parts of each item directly in a loop.
It is very useful with maps and pairs.
It keeps your code simple and clear.