如何以特定值对列表进行分块? [科特林]

时间:2021-02-04 21:59:29

标签: list kotlin chunked windowed

如何以特定值对列表进行分块?

例如:分割当前值为 5

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

将 x 转换为:

x => [[1,2,3,4,5],[2,3,1,5],[4,1,5]]

1 个答案:

答案 0 :(得分:1)

令人惊讶的是,在标准库中没有一种方法可以做到这一点。不过自己写一个也不难,比如:

/**
 * Splits a collection into sublists, following each occurrence of the given separator.
 */
fun <T> Collection<T>.splitAfter(separator: T): List<List<T>> {
    val result = mutableListOf<MutableList<T>>()
    
    var newSublist = true
    for (item in this) {
        if (newSublist)
            result += mutableListOf<T>()
        result.last() += item
        newSublist = (item == separator)
    }
    
    return result
}

按要求执行:

val x = listOf(1, 2, 3, 4, 5, 2, 3, 1, 5, 4, 1, 5)
println(x.splitAfter(5)) // prints [[1, 2, 3, 4, 5], [2, 3, 1, 5], [4, 1, 5]]

它还处理所有极端情况:空列表、连续分隔符以及零个或多个前导和/或尾随分隔符,例如:

val x = listOf(5, 5, 4, 5, 5, 2)
println(x.splitAfter(5)) // prints [[5], [5], [4, 5], [5], [2]]

(当然,最好包含涵盖所有此类情况的单元测试。)