0
0
Kotlinprogramming~5 mins

Zip for combining collections in Kotlin

Choose your learning style9 modes available
Introduction

Zip helps you join two lists together by pairing their items one by one. It makes working with two collections easy and organized.

When you have two lists of related data and want to process them together.
When you want to combine names and ages from separate lists into pairs.
When you need to compare items from two collections side by side.
When you want to create pairs of questions and answers from two lists.
When you want to loop through two lists at the same time.
Syntax
Kotlin
val zippedList = list1.zip(list2)

// Or with a transform function:
val zippedList = list1.zip(list2) { item1, item2 -> transformResult }

The zip function pairs elements by their positions: first with first, second with second, and so on.

If the lists have different sizes, the result length matches the smaller list.

Examples
This pairs numbers with words into a list of pairs.
Kotlin
val numbers = listOf(1, 2, 3)
val words = listOf("one", "two", "three")
val zipped = numbers.zip(words)
println(zipped)
This uses a transform to create a list of strings describing scores.
Kotlin
val names = listOf("Alice", "Bob")
val scores = listOf(90, 85)
val result = names.zip(scores) { name, score -> "$name scored $score" }
println(result)
Sample Program

This program pairs fruits with their colors and prints sentences describing each fruit's color.

Kotlin
fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry")
    val colors = listOf("Red", "Yellow", "Dark Red")

    val fruitColors = fruits.zip(colors) { fruit, color -> "$fruit is $color" }

    for (description in fruitColors) {
        println(description)
    }
}
OutputSuccess
Important Notes

Zip stops at the shortest list length, so extra items in longer lists are ignored.

You can use zip without a transform to get pairs, or with a transform to customize the output.

Summary

Zip combines two collections by pairing their elements in order.

The result length matches the smaller collection.

You can transform pairs into any result you want using a lambda.