首页 > 解决方案 > 在 Kotlin 中将一对列表展平为列表的惯用方法

问题描述

标题应该非常具有解释性。我有List<Pair<T, T>>并且我想以惯用和(更重要的是)有效的方式将它转换List<T>为所有对中的所有元素。

我知道有,flatten但它适用于List<List<T>>->的情况List<T>

现在我想出了两个实现作为扩展函数:

fun <T> List<Pair<T, T>>.flatten(): List<T> {
    val accumulator = mutableListOf<T>()
    this.forEach {
        accumulator.add(it.first)
        accumulator.add(it.second)
    }
    return accumulator
}

fun <T> List<Pair<T, T>>.flatten2(): List<T> {
    return this.fold(mutableListOf()) { accumulator: MutableList<T>, pair: Pair<T, T> ->
        accumulator.add(pair.first)
        accumulator.add(pair.second)
        accumulator
    }
}

但它们似乎并不优雅。

能否做得更好(在可读性、效率和惯用性方面)?

标签: kotlin

解决方案


我认为您的两个解决方案都非常易读,因此您不需要太多改进。

就效率而言,这种情况下的循环总是最好的,尽管您应该预先分配列表的大小以进一步优化它:

val accumulator = ArrayList<T>(size * 2)

就它的惯用而言,我真的认为对于一个简单的扩展功能,它不需要比这更好。显而易见的方法是使用 aflatMap作为其他答案提到的,但是在我看来,这在不需要时会降低效率。在两者中,第二个更惯用,性能应该相同,所以请根据您的喜好选择。


推荐阅读