Home > database >  Kotlin: zip two lists with index
Kotlin: zip two lists with index

Time:02-04

Is there a way to zip two lists in Kotlin, knowing current index in the transform lambda?

Something like this?

val list1 = listOf("a", "b", "c")
val list2 = listOf("x", "y", "z")
val joined = list1.zipWithIndex(list2){ a,b,i -> listOf(a,b,c)}

print(joined) // [[a, x, 0], [b, y, 1], [c, z, 2]]

CodePudding user response:

If you have only 2 lists, then the closest you can get is probably by using withIndex() and then destructuring inside the lambda passed to zip():

list1.withIndex().zip(list2) { (i, a), b -> listOf(i, a, b) }

Comparing to the solution in the comment, this may be a little more confusing as we first add index and then the second list, but this way we don't need map() and as we receive 2 arguments in the lambda we can destructure them fully.

  • Related