简体   繁体   English

如何在 Kotlin 中压缩列表并跳过下一步?

[英]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)] .我希望像[1,2,3,4,5]这样的列表是[(1,2),(3,4),(5,0 or null)]

What operation should I use in Kotlin or Java.我应该在 Kotlin 或 Java 中使用什么操作。

And I tried zipWithNext, it will be [(1,2),(2,3),(3,4),(4,5)]我试过 zipWithNext,它将是[(1,2),(2,3),(3,4),(4,5)]

chunked is the closest standard library function for this: chunked是最接近的标准库函数:

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:如果在最后一个块中需要0null ,我只需在调用此函数之前相应地填充列表:

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)你也可以使用这个函数:list.windowed(2, 2, true)

windowed is more flexible function, just look: windowed 是更灵活的功能,看看:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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