如果我有以下数组:
[1,1,1,2,2,1,1,1,1,2,2,3]
Run Code Online (Sandbox Code Playgroud)
Kotlin 中是否有任何内置方法可以过滤掉具有相同值的相邻元素,从而导致:
[1,2,1,2,3]
Run Code Online (Sandbox Code Playgroud)
保留顺序很重要。
PS 我的实际用例不是整数,它是一个实现 equals 的对象。
我认为没有标准函数可以做到这一点。但构建一个很容易mapOrNull:
fun <T : Any> Iterable<T>.removeAdjacent(): List<T> {
var last: T? = null
return mapNotNull {
if (it == last) {
null
} else {
last = it
it
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
661 次 |
| 最近记录: |