Skip to content
Permalink
Browse files

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

#KT-5793 Fixed
  • Loading branch information...
ilya-g committed Jul 14, 2015
1 parent f604eef commit da3ec891d0b476b26881bd122dcb63c24d42b711
@@ -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
}
@@ -621,6 +621,19 @@ class CollectionTest {
assertEquals(e, 5)
}

test fun unzipList() {
val list = listOf(1 to 'a', 2 to 'b', 3 to 'c')
val (ints, chars) = list.unzip()
assertEquals(listOf(1, 2, 3), ints)
assertEquals(listOf('a', 'b', 'c'), chars)
}

test fun unzipArray() {
val array = arrayOf(1 to 'a', 2 to 'b', 3 to 'c')
val (ints, chars) = array.unzip()
assertEquals(listOf(1, 2, 3), ints)
assertEquals(listOf('a', 'b', 'c'), chars)
}

test fun specialLists() {
compare(arrayListOf<Int>(), listOf<Int>()) { listBehavior() }
@@ -291,8 +291,7 @@ public class SequenceTest {
assertEquals(listOf(0, 1, 3, 4), result.toList())
}

test
fun flatten() {
test fun flatten() {
val data = sequenceOf(1, 2).map { sequenceOf(0..it) }
assertEquals(listOf(0, 1, 0, 1, 2), data.flatten().toList())
}
@@ -307,6 +306,12 @@ public class SequenceTest {
assertEquals(listOf(13, 34, 55, 144), sequence.distinctBy { it % 4 }.toList())
}

test fun unzip() {
val seq = sequenceOf(1 to 'a', 2 to 'b', 3 to 'c')
val (ints, chars) = seq.unzip()
assertEquals(listOf(1, 2, 3), ints)
assertEquals(listOf('a', 'b', 'c'), chars)
}

/*
test fun pairIterator() {

0 comments on commit da3ec89

Please sign in to comment.
You can’t perform that action at this time.