提问人:kkkkk 提问时间:11/17/2023 更新时间:11/17/2023 访问量:27
Kotlin 对具有相同类型的项目进行分组,以保留顺序
Kotlin group following items with a same type preserving an order
问:
我想将列表中的项目分组,并具有相同的类型、保留和排序。但前提是他们互相跟随。 有没有比简单更聪明的方法?
输入:
A A B A A A A C C A
输出:
A A
B
A A A A
C C
A
答:
1赞
AndrewL
11/17/2023
#1
下面是一个使用 Sequence 的解决方案
fun collectSame(src: List<String>): Sequence<Pair<String, List<String>>> = sequence {
var currentGroupKey: String? = null
val collector = mutableListOf<String>()
src.forEach {
if(currentGroupKey==null || currentGroupKey != it) {
currentGroupKey = it
if(collector.isNotEmpty()) {
yield(currentGroupKey!! to collector)
collector.clear()
}
}
collector.add(it)
}
}
fun main(args: Array<String>) {
val answer = collectSame(listOf("A","A","B","A","A","A","A","C","C","A"))
answer.forEach {
println(it.second)
}
}
输出
[A, A]
[B]
[A, A, A, A]
[C, C]
可能有一些方法可以比我的解决方案做得更好。grouping
1赞
lukas.j
11/17/2023
#2
val list = listOf("A", "A", "B", "A", "A", "A", "A", "C", "C", "A")
val result = list.foldIndexed(mutableListOf<MutableList<String>>()) { index, acc, value ->
when {
index > 0 && list[index - 1] == value -> acc.last().add(value)
else -> acc.add(mutableListOf(value))
}
acc
}
result.forEach(::println)
上一个:如何向后遍历 STL 列表?
评论