Lovis
Lovis

Reputation: 10057

Kotlin Zip only every second element

I have a List and I basically want to zip it, but only every second entry.

What I mean is: I want my List [a,1,b,2] to become [(a,1),(b,2)], I currently use zipWith.
But it does not give me the expected result, it gives me [(a,1),(1,b),(b,2)].

Am I being completely stupid right now, or is there no other solution than just ignore every second tuple? (e.g. by adding a filter afterwards) Is there no operator for that?

Upvotes: 3

Views: 1124

Answers (1)

yole
yole

Reputation: 97258

The chunked function in Kotlin 1.2 does exactly what you need:

val list = listOf("a", 1, "b", 2)
val newList = list.chunked(2)  // returns listOf(listOf("a", 1), listOf("b", 2))

Upvotes: 8

Related Questions