kotlin - 在 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
}
}
但它们似乎并不优雅。
能否做得更好(在可读性、效率和惯用性方面)?
解决方案
我认为您的两个解决方案都非常易读,因此您不需要太多改进。
就效率而言,这种情况下的循环总是最好的,尽管您应该预先分配列表的大小以进一步优化它:
val accumulator = ArrayList<T>(size * 2)
就它的惯用而言,我真的认为对于一个简单的扩展功能,它不需要比这更好。显而易见的方法是使用 aflatMap
作为其他答案提到的,但是在我看来,这在不需要时会降低效率。在两者中,第二个更惯用,性能应该相同,所以请根据您的喜好选择。
推荐阅读
- php - 如何获得蒸汽水平并检查某人是否至少有蒸汽水平 2
- sql - 交叉连接两个大表以获得运行总数的有效替代方法是什么?
- python - Scipy interp2d 函数产生 z = f(x,y),我想求解 x
- rholang - Rholang:@process 和 *name 有什么区别
- windows - 在 dockerfile 中多次切换转义字符
- game-maker - 通用汽车的简单但精确的基准
- javascript - 如何将字符串解析为 javascript 对象?
- angular-cli - 失败:模板解析错误:无法绑定到“可见”,因为它不是“p-dialog”的已知属性
- c++ - sqlite3 绑定多个语句值
- python - 列值到具有 ID 的列