RainFool
RainFool

Reputation: 466

How do I zip a list and skip next in Kotlin?

I hope a list like [1,2,3,4,5] would be [(1,2),(3,4),(5,0 or null)].

What operation should I use in Kotlin or Java.

And I tried zipWithNext, it will be [(1,2),(2,3),(3,4),(4,5)]

Upvotes: 3

Views: 1734

Answers (3)

Alex F.
Alex F.

Reputation: 41

Also you can do it this way:

val list = listOf(1, 2, 3, 4, 5)
with(list.windowed(2, 2, true))
{
    var newMutableList: MutableList<List<Int>> =
        ArrayList(0)
    if (size > 0 && size % 2 != 0) {
        newMutableList = this.toMutableList()
        newMutableList[newMutableList.lastIndex] += listOf(0)
    }

    if (newMutableList.isEmpty()) this else newMutableList
}

Upvotes: 0

Alex F.
Alex F.

Reputation: 41

You else can use this function: list.windowed(2, 2, true)

windowed is more flexible function, just look:

val list = listOf(1, 2, 3, 4, 5)
list.windowed(2, 2, true) {
    if (it.size % 2 != 0) listOf(it.first(), null) else it.toList()
} // [[1, 2], [3, 4], [5, null]]

Upvotes: 4

zsmb13
zsmb13

Reputation: 89608

chunked is the closest standard library function for this:

val list = listOf(1, 2, 3, 4, 5)
list.chunked(2) // [[1, 2], [3, 4], [5]]

If you need a 0 or null in the last chunk, I'd just pad the list accordingly before calling this function:

val list = listOf(1, 2, 3, 4, 5)

val paddedList = if (list.size % 2 == 0) list else (list + 0) // [1, 2, 3, 4, 5, 0]

paddedList.chunked(2) // [[1, 2], [3, 4], [5, 0]]

Upvotes: 7

Related Questions