Provide unzip method for Iterables, Arrays and Sequences of pairs.

#KT-5793 Fixed
This commit is contained in:
Ilya Gorbunov
2015-07-14 16:23:32 +03:00
parent f604eef2fe
commit da3ec891d0
3 changed files with 65 additions and 2 deletions
@@ -32,3 +32,48 @@ public fun <T> Array<Array<out T>>.flatten(): List<T> {
return result
}
/**
* Returns a pair of lists, where
* *first* list is built from the first values of each pair from this collection,
* *second* list is built from the second values of each pair from this collection.
*/
public fun <T, R> Iterable<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
val expectedSize = collectionSizeOrDefault(10)
val listT = ArrayList<T>(expectedSize)
val listR = ArrayList<R>(expectedSize)
for (pair in this) {
listT.add(pair.first)
listR.add(pair.second)
}
return listT to listR
}
/**
* Returns a pair of lists, where
* *first* list is built from the first values of each pair from this array,
* *second* list is built from the second values of each pair from this array.
*/
public fun <T, R> Array<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
val listT = ArrayList<T>(size())
val listR = ArrayList<R>(size())
for (pair in this) {
listT.add(pair.first)
listR.add(pair.second)
}
return listT to listR
}
/**
* Returns a pair of lists, where
* *first* list is built from the first values of each pair from this sequence,
* *second* list is built from the second values of each pair from this sequence.
*/
public fun <T, R> Sequence<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
val listT = ArrayList<T>()
val listR = ArrayList<R>()
for (pair in this) {
listT.add(pair.first)
listR.add(pair.second)
}
return listT to listR
}