Mapping class operators

1.1 flatMap series

flatMap(transform: (T) -> Iterable<R>)

  • The basic definition

    Combine the two sets according to the conditions to form a new set

  • Source code definition and parsing

    public inline fun <T, R>可迭代<T>.flatMap(transform: (T) - >可迭代<R>): List<R> {
        return flatMapTo(ArrayList<R>(), transform)
    }
    
    /** * Appends all elements yielded from results of [transform] function being invoked on each element of original collection, to the given [destination]. */
    public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) - >可迭代<R>): C {
        for (element in this) {
            val list = transform(element)
            destination.addAll(list)
        }
        return destination
    }
    Copy the code

    FlatMap is an extension function implemented with the help of the flatMapTo function

    Create an ArrayList mutable collection of R generics passed in from the external R generics to collect collections of conditional transformations. The inner part of flatMapTo is traversing the set, conditionally transforming the elements in the set, adding them to the set, and finally returning the set

  • Use the sample

    The flatMap operator is useful for merging two collections based on conditions to form a new collection

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.flatMap { listOf(it.plus("kotlin"))})}/****** The result is printed ******/
    [javakotlin, javaScriptkotlin, kotlinkotlin, Ckotlin, C++kotlin, javaFxkotlin, pythonkotlin, Gokotlin, Swiftkotlin, Scalakotlin]
    Copy the code

flatMapTo(destination: C, transform: (T) -> Iterable<R>)

  • The basic definition

    Combine the two sets according to the conditions to form a new set

  • Source code definition and parsing

    /** * Appends all elements yielded from results of [transform] function being invoked on each element of original collection, to the given [destination]. */
    public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) - >可迭代<R>): C {
        for (element in this) {
            val list = transform(element)
            destination.addAll(list)
        }
        return destination
    }
    Copy the code
  • Use the sample

    The flatMapTo operator is suitable for: conditional merging of multiple collections

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        val strList2 = listOf("11"."22"."33")
        val resultList = mutableListOf<String>().apply {
            strList.flatMapTo(this) {
                listOf(it.plus("kotlin"))
            }
            strList2.flatMapTo(this) {
                listOf(it.plus("kotlin"))
            }
        }
        print(resultList)
    
    }
    /****** The result is printed ******/
    [javakotlin, javaScriptkotlin, kotlinkotlin, Ckotlin, C++kotlin, javaFxkotlin, pythonkotlin, Gokotlin, Swiftkotlin, Scalakotlin, 11kotlin, 22kotlin, 33kotlin]
    Copy the code

1.2 group series

groupBy(keySelector: (T) -> K)

  • The basic definition

    Grouping operator that accepts one or two lambda expressions and returns a Map

  • Source code definition and parsing

    public inline fun <T, K>可迭代<T>.groupBy(keySelector: (T) - >K): Map<K, List<T>> {
        return groupByTo(LinkedHashMap<K, MutableList<T>>(), keySelector)
    }
    
    public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) - >K): M {
        for (element in this) {
            val key = keySelector(element)
            val list = destination.getOrPut(key) { ArrayList<T>() }
            list.add(element)
        }
        return destination
    }
    
    public inline fun <K, V> MutableMap<K, V>.getOrPut(key: K, defaultValue: () -> V): V {
        val value = get(key)
        return if (value == null) {
            val answer = defaultValue()
            put(key, answer)
            answer
        } else {
            value
        }
    }
    Copy the code

    GroupBy is an extension function implemented with the groupByTo function

  • Use the sample

    The groupBy operator is useful for splitting a collection into a map-type collection based on criteria

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.groupBy { if (it.startsWith("java")) "java" else "kotlin"})}/****** The result is printed ******/
    {java=[java, javaScript, javaFx], kotlin=[kotlin, C, C++, python, Go, Swift, Scala]}
    Copy the code

groupByTo(destination: M, keySelector: (T) -> K)

  • The basic definition

    Grouping operation

  • Source code definition and parsing

    public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) - >K): M {
        for (element in this) {
            val key = keySelector(element)
            val list = destination.getOrPut(key) { ArrayList<T>() }
            list.add(element)
        }
        return destination
    }
    Copy the code
  • Use the sample

    Grouping operation, suitable for grouping operation of multiple collections

    fun main(args: Array<String>) {
        val strList = listOf<String>("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        val numberList = listOf("111"."222"."333"."444"."555")
        val mutableMap = mutableMapOf<String,MutableList<String>>().apply {
            strList.groupByTo(this) {
                if (it.startsWith("java")) "java" else "not java"
            }
            numberList.groupByTo(this) {
                if (it.startsWith("222")) "222" else "not 222"
            }
        }
        print(mutableMap)
    }
    /****** The result is printed ******/
    {java=[java, javaScript, javaFx], not java=[kotlin, C, C++, python, Go, Swift, Scala], not 222= [111.333.444.555].222= [222]}
    Copy the code

groupingBy(crossinline keySelector: (T) -> K)

  • The basic definition

    Group the elements, and then apply the action to all the groups at once

  • Source code definition and parsing

    /**
     * Creates a [Grouping] source from a collection to be used later with one of group-and-fold operations
     * using the specified [keySelector] function to extract a key from each element.
     * 
     * @sample samples.collections.Grouping.groupingByEachCount
     */
    @SinceKotlin("1.1")
    public inline fun <T, K>可迭代<T>.groupingBy(crossinline keySelector: (T) - >K): Grouping<T, K> {
        return object : Grouping<T, K> {
            override fun sourceIterator(a): Iterator<T> = this@groupingBy.iterator()
            override fun keyOf(element: T): K = keySelector(element)
        }
    }
    
    @SinceKotlin("1.1")
    public interface Grouping<T, out K> {
        /** Returns an [Iterator] over the elements of the source of this grouping. */
        fun sourceIterator(a): Iterator<T>
        /** Extracts the key of an [element]. */
        fun keyOf(element: T): K
    }
    Copy the code

    Grouping supports the following operations:

    • EachCount () counts the elements in each group.
    • Fold () and reduce() perform fold and reduce operations on each group, respectively, as a separate collection and return the result.
    • aggregate()The given action is then applied to all elements in each group and the result is returned. This is theGroupingA common way to perform any operation. It can be used for custom operations when folding or shrinking is insufficient.
  • Use the sample

    The groupingBy operator is useful for complex grouping of collections

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.groupingBy { it.startsWith("java") }.eachCount())
    }
    /****** The result is printed ******/
    {true=3.false=7}
    Copy the code

1.3 the map series

map(transform: (T) -> R)

  • The basic definition

    Each element is converted in a specific way to form a new collection

  • Source code definition and parsing

    /** * Returns a list containing the results of applying the given [transform] function * to each element in the original  collection. * *@sample samples.collections.Collections.Transformations.map
     */
    public inline fun <T, R>可迭代<T>.map(transform: (T) - >R): List<R> {
        return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
    }
    
    
    public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) - >R): C {
        for (item in this)
            destination.add(transform(item))
        return destination
    }
    Copy the code

    The map operator is implemented with the help of the mapTo operator

  • Use the sample

    The map operator is useful for: set transformations, iterating over each element and executing a given expression, eventually forming a new set

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.map{it.plus("kotlin")})}/****** The result is printed ******/
    [javakotlin, javaScriptkotlin, kotlinkotlin, Ckotlin, C++kotlin, javaFxkotlin, pythonkotlin, Gokotlin, Swiftkotlin, Scalakotlin]
    Copy the code

mapTo(destination: C, transform: (T) -> R)

  • The basic definition

    Each element is converted in a specific way to form a new collection

  • Source code definition and parsing

    /** * Applies the given [transform] function to each element of the original collection * and appends the results to the  given [destination]. */
    public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) - >R): C {
        for (item in this)
            destination.add(transform(item))
        return destination
    }
    Copy the code
  • Use the sample

    The mapTo operator is useful for converting elements of multiple collections

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(mutableListOf<String>().apply {
            strList.mapTo(this){
                it.plus("kotlin")}}}/****** The result is printed ******/
    [javakotlin, javaScriptkotlin, kotlinkotlin, Ckotlin, C++kotlin, javaFxkotlin, pythonkotlin, Gokotlin, Swiftkotlin, Scalakotlin]
    Copy the code

mapIndexed(transform: (index: Int, T) -> R)

mapIndexedTo(destination: C, transform: (index: Int, T) -> R)

  • The basic definition

    Each element is converted in a specific way, but it can manipulate the index of the element to form a new set

  • Source code definition and parsing

    public inline fun <T, R>可迭代<T>.mapIndexed(transform: (index: Int.T) - >R): List<R> {
        return mapIndexedTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
    }
    
    public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapIndexedTo(destination: C, transform: (index: Int.T) - >R): C {
        var index = 0
        for (item in this)
            destination.add(transform(checkIndexOverflow(index++), item))
        return destination
    }
    Copy the code
  • Use the sample

    The mapIndexed operator is useful for: collection transformations with index subscripts of elements

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.mapIndexed{index, s ->  "$index$s"})}/****** The result is printed ******/
    [0java, 1javaScript, 2kotlin, 3C, 4C++, 5javaFx, 6python, 7Go, 8Swift, 9Scala]
    Copy the code

    The mapIndexedTo operator works with: multiple collection conversions with element index subscripts

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(mutableListOf<String>().apply {
            strList.mapIndexedTo(this) { index, s ->
                "$index$s"}})}/****** The result is printed ******/
    [0java, 1javaScript, 2kotlin, 3C, 4C++, 5javaFx, 6python, 7Go, 8Swift, 9Scala]
    Copy the code

mapNotNull(transform: (T) -> R?)

mapNotNullTo(destination: C, transform: (T) -> R?)

  • The basic definition

    The map{} function filters out elements that are null after the transform

  • Source code definition and parsing

    public inline fun <T, R : Any>可迭代<T>.mapNotNull(transform: (T) - >R?).: List<R> {
        return mapNotNullTo(ArrayList<R>(), transform)
    }
    
    public inline fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapNotNullTo(destination: C, transform: (T) - >R?).: C { forEach { element -> transform(element)? .let { destination.add(it) } }return destination
    }
    Copy the code
  • Use the sample

    The mapNotNull operator applies to scenarios similar to map, except that it filters elements that are null after the collection is transformed

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.mapNotNull { if (it.startsWith("java")) null else it})
    }
    /****** The result is printed ******/
    [kotlin, C, C++, python, Go, Swift, Scala]
    Copy the code
The 'mapNotNullTo' operator is suitable for multi-set operations ** 'mapIndexedNotNull' is the same as' mapIndexedNotNullTo ' ** 'elementAt(index: Int)' ** - ** 'kotlin public fun <T> Iterable<T>. ElementAt (index: Int): T {if (this is List) return get(index) return elementAtOrElse(index) {throw IndexOutOfBoundsException("Collection doesn't contain element at index $index.") } } public fun <T> Iterable<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T { if (this is List) return this.getOrElse(index, defaultValue) if (index < 0) return defaultValue(index) val iterator = iterator() var count = 0 while (iterator.hasNext()) { val element = iterator.next() if (index == count++) return element } return defaultValue(index) }  @kotlin.internal.InlineOnly public inline fun <T> List<T>.getOrElse(index: Int, defaultValue: (Int) -> T): T { return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index) }Copy the code
  • Use the sample

    The elementAt operator is used to: get elements with the specified subscript of the collection

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.elementAt(3))}/****** The result is printed ******/
    C
    Copy the code

elementAtOrElse(index: Int, defaultValue: (Int) -> T)

  • The basic definition

    Gets the collection element of the corresponding subscript. If the subscript is out of bounds, the default value is returned

  • Source code definition and parsing

    /** * Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out  of bounds of this collection. * *@sample samples.collections.Collections.Elements.elementAtOrElse
     */
    public fun <T>可迭代<T>.elementAtOrElse(index: Int, defaultValue: (Int) - >T): T {
        if (this is List)
            return this.getOrElse(index, defaultValue)
        if (index < 0)
            return defaultValue(index)
        val iterator = iterator()
        var count = 0
        while (iterator.hasNext()) {
            val element = iterator.next()
            if (index == count++)
                return element
        }
        return defaultValue(index)
    }
    Copy the code
  • Use the sample

    The elementAtOrElse operator applies to: Get the collection element with the corresponding subscript. If the subscript is out of bounds, the default value is returned

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.elementAtOrElse(13) {"defaultView"})}/****** The result is printed ******/
    defaultView
    Copy the code

elementAtOrNull(index: Int)

  • The basic definition

    Gets the collection element of the corresponding subscript. If the subscript is out of bounds, null is returned

  • Source code definition and parsing

    public fun <T>可迭代<T>.elementAtOrNull(index: Int): T? {
        if (this is List)
            return this.getOrNull(index)
        if (index < 0)
            return null
        val iterator = iterator()
        var count = 0
        while (iterator.hasNext()) {
            val element = iterator.next()
            if (index == count++)
                return element
        }
        return null
    }
    Copy the code
  • Use the sample

    The elementAtOrNull operator is used to get the specified subscript element of a collection and return NULL out of bounds

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.elementAtOrNull(13))}/****** The result is printed ******/
    null
    Copy the code

2.2 First and last series

first()

  • The basic definition

    Gets the first element of the collection, which throws a NoSuchElementException if the collection is empty

  • Source code definition and parsing

    public fun <T> List<T>.first(a): T {
        if (isEmpty())
            throw NoSuchElementException("List is empty.")
        return this[0]}public fun <T>可迭代<T>.first(a): T {
        when (this) {
            is List -> return this.first()
            else- > {val iterator = iterator()
                if(! iterator.hasNext())throw NoSuchElementException("Collection is empty.")
                return iterator.next()
            }
        }
    }
    Copy the code
  • Use the sample

    The first operator applies to: Get the first element of a collection

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.first())
    }
    /****** The result is printed ******/
    java
    Copy the code

first(predicate: (T) -> Boolean)

  • The basic definition

    Gets the first element in the collection for the specified condition. If the conditions are not met, an exception is thrown

  • Source code definition and parsing

    public inline fun <T>可迭代<T>.first(predicate: (T) - >Boolean): T {
        for (element in this) if (predicate(element)) return element
        throw NoSuchElementException("Collection contains no element matching the predicate.")}Copy the code
  • Use the sample

    The first{} operator is used to: get the first element in the collection that satisfies a condition

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.first { it.length == 6})}/****** The result is printed ******/
    kotlin
    Copy the code

firstOrNull()

  • The basic definition

    Gets the first element of the collection, or null if the collection is empty

  • Source code definition and parsing

    ublic fun <T>可迭代<T>.firstOrNull(a): T? {
        when (this) {
            is List -> {
                if (isEmpty())
                    return null
                else
                    return this[0]}else- > {val iterator = iterator()
                if(! iterator.hasNext())return null
                return iterator.next()
            }
        }
    }
    
    
    public fun <T> List<T>.firstOrNull(a): T? {
        return if (isEmpty()) null else this[0]}Copy the code
  • Use the sample

    The firstOrNull operator is used to retrieve the first element of a collection or return NULL for an empty collection

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.firstOrNull())
    }
    /****** The result is printed ******/
    java
    Copy the code

note

The firstOrNull{} operator is used to get the first element of the collection that meets the criteria, or return NULL if there is none

fun main(args: Array<String>) {
    val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
    print(strList.firstOrNull{
        it.endsWith("language")})}/****** The result is printed ******/
null
Copy the code

Corresponding to operators such as first are related operators such as last, which take the last element of the set, etc

2.3 find series

find(predicate: (T) -> Boolean)

  • The basic definition

    FirstOrNull {} Returns the first element of the set that meets the criteria.

  • Source code definition and parsing

    @kotlin.internal.InlineOnly
    public inline fun <T>可迭代<T>.find(predicate: (T) - >Boolean): T? {
        return firstOrNull(predicate)
    }
    Copy the code
  • Use the sample

    The use scenario of the find operator is the same as firstOrNull{}

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.find{
            it.endsWith("t")})}/****** The result is printed ******/
    javaScript
    Copy the code

findLast(predicate: (T) -> Boolean)

  • The basic definition

    LastOrNull {} Returns the last element of the set that meets the criteria.

  • Source code definition and parsing

    @kotlin.internal.InlineOnly
    public inline fun <T>可迭代<T>.findLast(predicate: (T) - >Boolean): T? {
        return lastOrNull(predicate)
    }
    
    @kotlin.internal.InlineOnly
    public inline fun <T> List<T>.findLast(predicate: (T) - >Boolean): T? {
        return lastOrNull(predicate)
    }
    Copy the code
  • Use the sample

    The findLast operator is used to retrieve the last element of the collection that meets the criteria, or to return NULL if there is none

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.findLast{
            it.endsWith("t")})}/****** The result is printed ******/
    Swift
    Copy the code

2.4 single series

single()

  • The basic definition

    If there is only one element in the collection, that element is returned, otherwise an exception is thrown

  • Source code definition and parsing

    public fun <T>可迭代<T>.single(a): T {
        when (this) {
            is List -> return this.single()
            else- > {val iterator = iterator()
                if(! iterator.hasNext())throw NoSuchElementException("Collection is empty.")
                val single = iterator.next()
                if (iterator.hasNext())
                    throw IllegalArgumentException("Collection has more than one element.")
                return single
            }
        }
    }
    
    public fun <T> List<T>.single(a): T {
        return when (size) {
            0 -> throw NoSuchElementException("List is empty.")
            1 -> this[0]
            else -> throw IllegalArgumentException("List has more than one element.")}}Copy the code
  • Use the sample

    The single operator is useful for determining whether a collection has only one element

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        println(strList.single())
    }
    /****** The result is printed ******/
    java.lang.IllegalArgumentException: List has more than one element.
    Copy the code
    fun main(args: Array<String>) {
        val singleList = listOf<String>("java")
        println(singleList.single())
    }
    /****** The result is printed ******/
    java
    Copy the code

single(predicate: (T) -> Boolean)

  • The basic definition

    Find the element in the set that meets the condition. If only a single element meets the condition, return the element. Otherwise, throw an exception

  • Source code definition and parsing

    public inline fun <T>可迭代<T>.single(predicate: (T) - >Boolean): T {
        var single: T? = null
        var found = false
        for (element in this) {
            if (predicate(element)) {
                if (found) throw IllegalArgumentException("Collection contains more than one matching element.")
                single = element
                found = true}}if(! found)throw NoSuchElementException("Collection contains no element matching the predicate.")
        @Suppress("UNCHECKED_CAST")
        return single as T
    }
    Copy the code
  • Use the sample

    The single{} operator applies to finding only a single element in a collection that meets the criteria

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        println(strList.single{
            it.startsWith("py")})}/****** The result is printed ******/
    python
    Copy the code

note

The singleOrNull or singleOrNull{} operator simply returns NULL instead of throwing the previous exception

fun main(args: Array<String>) {
    val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
    println(strList.singleOrNull{
        it.startsWith("java")})}/****** The result is printed ******/
null
Copy the code

2.5 component series

component1()

component2()

.

  • The basic definition

    Used to get elements

  • Source code definition and parsing

    public inline operator fun <T> List<T>.component1(a): T {
        return get(0)}@kotlin.internal.InlineOnly
    public inline operator fun <T> List<T>.component2(a): T {
        return get(1)}/ /... Maximum component5
    Copy the code
  • Use the sample

    fun main(args: Array<String>) {
        val strList = listOf<String>("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        val numberList = listOf("111"."212"."332"."444"."555"."111"."666")
        print(numberList.component5())
    }
    /****** The result is printed ******/
    555
    Copy the code

2.6 indexOf series

indexOf(element: T)

  • The basic definition

    Returns the subscript of the specified element, or -1 if none exists

  • Source code definition and parsing

    public fun <@kotlin.internal.OnlyInputTypes T>可迭代<T>.indexOf(element: T): Int {
        if (this is List) return this.indexOf(element)
        var index = 0
        for (item in this) {
            checkIndexOverflow(index)
            if (element == item)
                return index
            index++
        }
        return -1
    }
    
    public fun <@kotlin.internal.OnlyInputTypes T> List<T>.indexOf(element: T): Int {
        return indexOf(element)
    }
    Copy the code
  • Use the sample

    fun main(args: Array<String>) {
        val strList = listOf<String>("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.indexOf("C"))}/****** The result is printed ******/
    3
    Copy the code

indexOfFirst(predicate: (T) -> Boolean)

  • The basic definition

    Returns the index of the first element that satisfies the condition, or -1 if none exists

  • Source code definition and parsing

    public inline fun <T>可迭代<T>.indexOfFirst(predicate: (T) - >Boolean): Int {
        var index = 0
        for (item in this) {
            checkIndexOverflow(index)
            if (predicate(item))
                return index
            index++
        }
        return -1
    }
    Copy the code
  • Use the sample

    The indexOfFirst operator is used to get the index of the first element that meets the criteria

    fun main(args: Array<String>) {
        val strList = listOf<String>("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.indexOfFirst {
            it.startsWith("S")})}/****** The result is printed ******/
    8
    Copy the code
  • note

    The indexOfLast operator, in contrast, takes the index of the last element that satisfies the condition

    fun main(args: Array<String>) {
        val strList = listOf<String>("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.indexOfLast {
            it.startsWith("S")})}/****** The result is printed ******/
    9
    Copy the code

Sort operators

3.1 reverse series

reverse()

reversed()

  • The basic definition

    Set element inversion

  • Source code definition and parsing

    /** * Reverses elements in the list in-place. */
    public expect fun <T> MutableList<T>.reverse(a): Unit
    
    /** * Returns a list with elements in reversed order. */
    public fun <T>可迭代<T>.reversed(a): List<T> {
        if (this is Collection && size <= 1) return toList()
        val list = toMutableList()
        list.reverse()
        return list
    }
    Copy the code
  • Usage scenarios and examples

    The reverse operator is used to reverse collection elements

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        println(strList.reversed())
    }
    /****** The result is printed ******/
    [Scala, Swift, Go, python, javaFx, C++, C, kotlin, javaScript, java]
    Copy the code

3.2 sort series

sorted()

  • The basic definition

    Sort the elements in a collection in natural ascending order

  • Source code definition and parsing

    public fun <T : Comparable<T>> Iterable<T>.sorted(a): List<T> {
        if (this is Collection) {
            if (size <= 1) return this.toList()
            @Suppress("UNCHECKED_CAST")
            return (toTypedArray<Comparable<T>>() as Array<T>).apply { sort() }.asList()
        }
        return toMutableList().apply { sort() }
    }
    Copy the code
  • Use the sample

    The sorted operator applies to: naturally ascending sorting of collection elements

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        println(strList.sorted())
    }
    /****** The result is printed ******/
    [C, C++, Go, Scala, Swift, java, javaFx, javaScript, kotlin, python]
    Copy the code

sortBy(crossinline selector: (T) -> R?)

  • The basic definition

    Returns a list sorted by the specified function.

  • Source code definition and parsing

    public inline fun <T, R : Comparable<R>> MutableList<T>.sortBy(crossinline selector: (T) - >R?).: Unit {
        if (size > 1) sortWith(compareBy(selector))
    }
    
    expect fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit
    Copy the code
  • Usage scenarios and examples

    The sortBy operator is used to sortBy the specified function

    fun main(args: Array<String>) {
        val mutableList = mutableListOf<String>("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        mutableList.sortBy {
            it.length
        }
        print(mutableList)
    }
    Copy the code

sortedBy(crossinline selector: (T) -> R?)

  • The basic definition

    In ascending order according to the conditions, that is, those that do not meet the conditions are put in front and those that do meet the conditions are put behind

  • Source code definition and parsing

    public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) - >R?).: List<T> {
        return sortedWith(compareBy(selector))
    }
    Copy the code
  • Usage scenarios and examples

    The sortedBy operator works by ascending by condition, putting those that do not meet the condition first and those that do follow

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        println(strList.sortedBy {
            it.length
        })
    }
    /****** The result is printed ******/
    [C, Go, C++, java, Swift, Scala, kotlin, javaFx, python, javaScript]
    Copy the code
  • note

    The sortedByDescending operator is the reverse of sortedBy

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        println(strList.sortedBy {
            it.length
        })
    }
    /****** The result is printed ******/
    [javaScript, kotlin, javaFx, python, Swift, Scala, java, C++, Go, C]
    Copy the code

4. Generate classes

4.1 partition series

partition(predicate: (T) -> Boolean)

  • The basic definition

    Split the collection into a new collection consisting of two pairs

  • Source code definition and parsing

    /**
     * Splits the original collection into pair of lists,
     * where *first* list contains elements for which [predicate] yielded `true`,
     * while *second* list contains elements for which [predicate] yielded `false`.
     * 
     * @sample samples.collections.Iterables.Operations.partition
     */
    public inline fun <T>可迭代<T>.partition(predicate: (T) - >Boolean): Pair<List<T>, List<T>> {
        val first = ArrayList<T>()
        val second = ArrayList<T>()
        for (element in this) {
            if (predicate(element)) {
                first.add(element)
            } else {
                second.add(element)
            }
        }
        return Pair(first, second)
    }
    Copy the code
  • Use the sample

    The partition operator is suitable for conditionally splitting a collection into a new collection of two pairs

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        println(strList.partition {
            it.startsWith("java")})}/****** The result is printed ******/
    ([java, javaScript, javaFx], [kotlin, C, C++, python, Go, Swift, Scala])
    Copy the code

4.2 plus series

plus(element: T)

  • The basic definition

    Combine elements from two sets to form a new set. You can also use the sign +

  • Source code definition and parsing

    /** * Returns a list containing all elements of the original collection and then the given [element]. */
    public operator fun <T>可迭代<T>.plus(element: T): List<T> {
        if (this is Collection) return this.plus(element)
        val result = ArrayList<T>()
        result.addAll(this)
        result.add(element)
        return result
    }
    
    public operator fun <T>可迭代<T>.plus(elements: Array<out T>): List<T> {
        if (this is Collection) return this.plus(elements)
        val result = ArrayList<T>()
        result.addAll(this)
        result.addAll(elements)
        return result
    }
    
    / /...
    Copy the code
  • Use the sample

    The plus operator is useful for: collection merging

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        val numberList = listOf<String>("111"."222"."333"."444")
        println(strList.plus(numberList))
    }
    /****** The result is printed ******/
    [java, javaScript, kotlin, C, C++, javaFx, python, Go, Swift, Scala, 111.222.333.444]
    Copy the code

plusElement(element: T)

  • The basic definition

    Adds an element to the collection

  • Source code definition and parsing

    @kotlin.internal.InlineOnly
    public inline fun <T>可迭代<T>.plusElement(element: T): List<T> {
        return plus(element)
    }
    
    @kotlin.internal.InlineOnly
    public inline fun <T> Collection<T>.plusElement(element: T): List<T> {
        return plus(element)
    }
    Copy the code
  • Usage scenarios and examples

    The plusElement operator applies to adding elements to a collection

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.plusElement("plusElement"))}/****** The result is printed ******/
    [java, javaScript, kotlin, C, C++, javaFx, python, Go, Swift, Scala, plusElement]
    Copy the code

4.3 zip series

zip(other: Array<out R>)

  • The basic definition

    A new set is formed from two sets with the same subscripts. The new collection is of type: List

  • Source code definition and parsing

    public infix fun <T, R>可迭代<T>.zip(other: Array<out R>): List<Pair<T, R>> {
        return zip(other) { t1, t2 -> t1 to t2 }
    }
    
    public inline fun <T, R, V>可迭代<T>.zip(other: Array<out R>, transform: (a: T.b: R) - >V): List<V> {
        val arraySize = other.size
        val list = ArrayList<V>(minOf(collectionSizeOrDefault(10), arraySize))
        var i = 0
        for (element in this) {
            if (i >= arraySize) break
            list.add(transform(element, other[i++]))
        }
        return list
    }
    
    / /...
    Copy the code
  • Use the sample

    The zip operator is used when elements of two collections are combined in pairs

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        val numberList = listOf("111"."222"."333"."444"."555")
        print(strList zip numberList)
    }
    /****** The result is printed ******/
    [(java, 111), (javaScript, 222), (kotlin, 333), (C, 444), (C++, 555)]
    Copy the code

zipWithNext()

zipWithNext(transform: (a: T, b: T) -> R)

  • The basic definition

    Sets and adjacent elements form pairs

  • Source code definition and parsing

    /**
     * Returns a list of pairs of each two adjacent elements in this collection.
     * 
     * The returned list is empty if this collection contains less than two elements.
     * 
     * @sample samples.collections.Collections.Transformations.zipWithNext
     */
    @SinceKotlin("1.2")
    public fun <T>可迭代<T>.zipWithNext(a): List<Pair<T, T>> {
        return zipWithNext { a, b -> a to b }
    }
    
    @SinceKotlin("1.2")
    public inline fun <T, R>可迭代<T>.zipWithNext(transform: (a: T.b: T) - >R): List<R> {
        val iterator = iterator()
        if(! iterator.hasNext())return emptyList()
        val result = mutableListOf<R>()
        var current = iterator.next()
        while (iterator.hasNext()) {
            val next = iterator.next()
            result.add(transform(current, next))
            current = next
        }
        return result
    }
    Copy the code
  • Use the sample

    The zipWithNext operator applies to neighboring elements in a set that form pairs

    fun main(args: Array<String>) {
        val strList = listOf("java"."javaScript"."kotlin"."C"."C++"."javaFx"."python"."Go"."Swift"."Scala")
        print(strList.zipWithNext() )
    }
    /****** The result is printed ******/
    [(java, javaScript), (javaScript, kotlin), (kotlin, C), (C, C++), (C++, javaFx), (javaFx, python), (python, Go), (Go, Swift), (Swift, Scala)]
    Copy the code