The title should be pretty much explanatory. I have List<Pair<T, T>> and I would like to transform it into List<T> with all elements from all of the pairs in an idiomatic and (more importantly) efficient way.
I know there's flatten but it's for the case of List<List<T>> -> List<T>.
For now I came up with two implementations as extension functions:
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
}
and
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
}
}
but they don't seem to be elegant.
Could it be done better (in terms of readability, efficiency and idiomaticness)?