Zip/Unzip

Not related to archiving in any way, zip() allows us to create pairs out of two lists based on their indexes. That may sound confusing, so let's look at an example.

We have two functions, one fetching all active employees, and the other for how many days the employee was employed in our startup:

val employeeIds = listOf(5, 8, 13, 21, 34, 55, 89)
val daysInCompany = listOf(176, 145, 117, 92, 70, 51, 35, 22, 12, 5)

Calling zip() between the two of them will produce the following result:

println(employeeIds.zip(daysInCompany))

The preceding code prints the following output:

[(5, 176), (8, 145), (13, 117), (21, 92), (34, 70), (55, 51), (89, 35)]

Note that since we had a bug in our second function, and returned the days for the employees that had already left our startup, the length of the two lists wasn't equal, to begin with. Calling zip() will always produce the shortest list of pairs:

println(daysInCompany.zip(employeeIds))

The preceding code prints the following output:

[(176, 5), (145, 8), (117, 13), (92, 21), (70, 34), (51, 55), (35, 89)]

Note that this is not a map, but a list of pairs.

Having such a list, we can also unzip it:

val employeesToDays = employeeIds.zip(daysInCompany)

val (employees, days) = employeesToDays.unzip()
println(employees)
println(days)

The preceding code prints the following:

[5, 8, 13, 21, 34, 55, 89]
[176, 145, 117, 92, 70, 51, 35]
..................Content has been hidden....................

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