The zip function

The zip function does exactly what it sounds like, it zips collections. Confusing? Let's have a look at the following example:

fun main(args: Array<String>) { 
    val list1 = listOf(1,2,3,4,5) 
    val list2 = listOf( 
            "Item 1", 
            "Item 2", 
            "Item 3", 
            "Item 4", 
            "Item 5" 
    ) 
 
    val resultantList = list1.zip(list2) 
 
    println(resultantList) 
} 

We created two lists—one with Int and the other with String. We then created a resultant list by zipping the Int list with the String list and printed the resultant list.

So, what does the resultantList value contain? What operation did the zip function perform?

Let us decide it ourselves by having a look at the following output:

Amazing, isn't it? The zip function takes another collection, combines the source collection with the provided collection, and creates a Pair value for each of the items. But what if the collections differ in item counts? What if we want to combine each item in a list with the next item in the same list?

Let's take another example. Have a look at the following code:

fun main(args: Array<String>) { 
    val list1 = listOf(1,2,3,4,5,6,7,8) 
    val list2 = listOf( 
            "Item 1", 
            "Item 2", 
            "Item 3", 
            "Item 4", 
            "Item 5" 
    ) 
 
    println("list1.zip(list2)-> ${list1.zip(list2)}") 
 
    println("list1.zipWithNext() -> ${list1.zipWithNext()}") 
} 

So, the first println statement here answers our first question—it tries to combine two lists with asymmetrical item counts.

On the second println statement, we used the zipWithNext function, which zips one item of a collection with the next item of the same collection. So, let's have a look at the output to find out what happens.

The following is the output:

So, the zip operator only zipped those items of list1, for which it could find a pair in list2 and skipped the remaining. The zipWithNext operator on the other hand, worked as expected.

So, we are done with data operation functions in Kotlin collection framework. However, Kotlin provides you with more capabilities for collections; so, let's move ahead and see what more it has to offer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.239.226