如何以特定值分块列表?
例如:当前值为 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]]
令人惊讶的是,标准库中没有一种方法可以做到这一点。但是自己写一个并不难,例如:
/**
* 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]]
(当然,包含涵盖所有此类情况的单元测试是个好主意。)