zip(other: Iterable<R>): List<Pair<T, R>>

    如果两个集合长度不一样,取短的长度。

    代码示例

    这个zip函数的定义如下:

    1. public infix fun <T, R> Iterable<T>.zip(other: Iterable<R>): List<Pair<T, R>> {
    2. return zip(other) { t1, t2 -> t1 to t2 }
    3. }

    我们可以看出,其内部是调用了zip(other) { t1, t2 -> t1 to t2 }。这个函数定义如下:

    1. public inline fun <T, R, V> Iterable<T>.zip(other: Iterable<R>, transform: (a: T, b: R) -> V): List<V> {
    2. val first = iterator()
    3. val second = other.iterator()
    4. val list = ArrayList<V>(minOf(collectionSizeOrDefault(10), other.collectionSizeOrDefault(10)))
    5. while (first.hasNext() && second.hasNext()) {
    6. list.add(transform(first.next(), second.next()))
    7. }
    8. return list
    9. }

    依次取两个集合相同索引的元素,使用提供的转换函数transform得到映射之后的值,作为元素组成一个新的List,并返回该List。列表的长度取两个集合中最短的。

    代码示例

    1. >>> val list1 = listOf(1,2,3)
    2. >>> val list2 = listOf(4,5,6,7)
    3. [x1, y2, z3]
    4. >>> list1.zip(list2, {t1,t2 -> t1*t2})
    5. [4, 10, 18]

    unzip(): Pair<List<T>, List<R>>

    函数定义

    看到这里,仍然有点抽象,我们直接看代码示例:

    1. >>> val listPair = listOf(Pair(1,2),Pair(3,4),Pair(5,6))
    2. >>> listPair
    3. [(1, 2), (3, 4), (5, 6)]
    4. >>> listPair.unzip()
    5. ([1, 3, 5], [2, 4, 6])

    partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>>

    根据判断条件是否成立,将集合拆分成两个子集合组成的 Pair。我们可以直接看函数的定义来更加清晰的理解这个函数的功能:

    1. public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
    2. val first = ArrayList<T>()
    3. val second = ArrayList<T>()
    4. for (element in this) {
    5. if (predicate(element)) {
    6. first.add(element)
    7. } else {
    8. second.add(element)
    9. }
    10. }

    我们可以看出,这是一个内联函数。

    代码示例

    1. >>> val list = listOf(1,2,3,4,5,6,7,8,9)
    2. >>> list
    3. [1, 2, 3, 4, 5, 6, 7, 8, 9]
    4. >>> list.partition({it>5})
    5. ([6, 7, 8, 9], [1, 2, 3, 4, 5])

    plus(elements: Iterable<T>): List<T>

    合并两个List。

    我们可以看出,这是一个操作符函数。可以用”+”替代 。

    代码示例

    1. >>> val list1 = listOf(1,2,3)
    2. >>> val list2 = listOf(4,5)
    3. >>> list1.plus(list2)
    4. [1, 2, 3, 4, 5]
    5. >>> list1+list2
    6. [1, 2, 3, 4, 5]

    关于plus函数还有以下的重载函数:

    1. plus(element: T): List<T>
    2. plus(elements: Array<out T>): List<T>
    3. plus(elements: Sequence<T>): List<T>

    等。

    plusElement(element: T): List<T>

    在集合中添加一个元素。 函数定义

    1. @kotlin.internal.InlineOnly
    2. public inline fun <T> Iterable<T>.plusElement(element: T): List<T> {
    3. return plus(element)
    4. }

    我们可以看出,这个函数内部是直接调用的plus(element: T): List<T>