简体   繁体   中英

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)]

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]]

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]]

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM