Kotlin将具有相同类型的项分组,并保持顺序

hivapdat  于 12个月前  发布在  Kotlin
关注(0)|答案(2)|浏览(139)

我想对列表中的项目进行分组,并保持相同的类型和顺序。但前提是它们彼此遵循。还有比simple for更聪明的方法吗?
输入:

A A B A A A A C C A

字符串
输出量:

A A
B
A A A A
C C 
A

sqyvllje

sqyvllje1#

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)

字符串
Kotlin Playground

v440hwme

v440hwme2#

这里有一个使用序列的解决方案

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解决方案更好地做到这一点。

相关问题