Kotlin系列之常用操作符

前言:

本篇文章來介紹下Kotlin的常用操作符。kotlin相對於java來說是一門十分簡潔的語言,這其中操作符起了很大的作用,這些操作符和Rxjava的類似,如果你熟悉Rxjava,那麼這些操作符學起來就得心應手很多,畢竟這些操作符還是挺簡單的說。。。

常用操作符大致可以分爲

  • 總數操作符
  • 過濾操作符
  • 映射操作符
  • 元素操作符
  • 生產操作符
  • 順序操作符

首先我想說的是,學習這些操作符應該從以下幾個方面進行
- 敲:在開發工具裏面敲這些代碼
- 看:點擊去看看操作符的源碼
- 跑:親自跑一下代碼,看看運行的結果
- 思:綜合思考這些操作符的意義,加深理解

- 總數操作符

private val list= listOf<Int>(0,1,2,3,4,5,6,7,8,9)

//any 只要有一個符合就返回true
val any= list.any { it>8 }

//all 所有條件符合才返回true
val all= list.all { it>0 }

//count 返回符合條件的數目
val count= list.count { it>5 }

//none 如果沒有任何元素與給定的函數匹配,則返回true
val none= list.none{it>10}

//fold 在一個初始值的基礎上 從第一項到最後一項通過 一個函數操作 所有的元素。
//下面是初始值4 每項進行累加
val fold= list.fold(4){total,next->total+next}

//foldRight與fold一樣,但是順序是從最後一項到第一項。注意與fold的區別,參數位置調過來了
val foldRight=list.foldRight(4) { next, total -> total + next }

//reduce 從第一項到最後一項通過 一個函數操作 所有的元素,相對於fold,沒有初始值
//reduceRight 是從後到前
val reduce= list.reduce { acc, i -> acc+i }

//forEach 遍歷每個元素並且進行操作
val foreach= list.forEach { println(it) }

//forEachIndexed 與foreach相同,但是可以得到index
val forEachIndexed= list.forEachIndexed { index, value -> println("$index -> $value")  }

//max 返回最大的值,如果沒有則返回null min同
val max=list.max()

//maxBy 根據指定的函數返回最大值 minBy同
val maxBy=list.maxBy { -it }

//sumBy 每項經過函數轉換後的和
val sumBy=list.sumBy { it+9 }

- 過濾操作符

private val list= listOf<Int>(0,1,2,3,4,5,6,5,4,3,2,1,0)

/**
 * drop 返回包含去掉前n個元素的所有元素的列表
 * Returns a list containing all elements except first [n] elements.
 * 返回[4, 5, 6, 5, 4, 3, 2, 1, 0]
 */
val drop= list.drop(4)

/**
 * dropwhile 根據特定的函數 從第一項開始 直到不滿足條件後返回 列表
 * Returns a list containing all elements except first elements that satisfy the given [predicate].
 * 返回[0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1, 0]
 */
val dropwhile=list.dropWhile {it > 1 }

/**
 * dropLastWhile 返回根據特定的函數 從最後一項開始 直到不滿足條件後返回 列表
 * Returns a list containing all elements except last elements that satisfy the given [predicate].
 * 返回[0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1, 0]
 */
val dropLastWhile= list.dropLastWhile { it>4 }

/**
 *filter 返回所有符合給定函數條件的元素。
 * Returns a list containing only elements matching the given [predicate].
 * [5, 6, 5]
 */
val filter=list.filter { it>4 }

/**
 * filterNot 返回所有不符合給定函數條件的元素
 * Returns a list containing all elements not matching the given [predicate].
 * [0, 1, 2, 3, 4, 4, 3, 2, 1, 0]
 */
val filterNot=list.filterNot { it>4 }

/**
 * filterNotNull 返回非null元素
 * Returns a list containing all elements that are not `null`.
 * [0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1, 0]
 */
val filterNotNull= list.filterNotNull()

/**
 * 返回滿足該ranger的元素集合
 * Returns a list containing elements at indices in the specified [indices] range.
 * [0, 1, 2, 3, 4, 5, 6]
 */
val slice= list.slice(0..6)

/**
 * listOf(0,4,7)是集合list的座標
 * Returns a list containing elements at specified [indices].
 * [0, 4, 5]
 */
val slice2= list.slice(listOf(0,4,7))

/**
 *返回前n項
 * Returns a list containing first [n] elements.
 * [0, 1, 2, 3]
 */
val take= list.take(4)

/**
 * 返回後n項
 * Returns a list containing last [n] elements.
 * [3, 2, 1, 0]
 */
val takeLast= list.takeLast(4)


/**
 * 從第一項開始判斷,直到不符合就返回,返回符合的前幾項數據
 * Returns a list containing first elements satisfying the given [predicate].
 * []
 */
val takeWhile= list.takeWhile { it>4 }

- 映射操作符

private val list= listOf(0,1,2,3,4,5,4,3,2,1,0,-1)

/**
 * 返回滿足條件的集合
 * Returns a list containing the results of applying the given [transform] function
 * to each element in the original collection.
 * [false, false, false, true, true, true, true, true, false, false, false, false]
 */
val map=list.map { it>2 }

/**
 * 返回特定函數後的集合,參數是Iterable類型,
 * Returns a single list of all elements yielded from results of [transform]
 * function being invoked on each element of original collection.
 * [0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 4, 5, 3, 4, 2, 3, 1, 2, 0, 1, -1, 0]
 */
val flatMap=list.flatMap { listOf(it, it + 1) }

/**
 * 根據函數將集合分組,返回map類型對象
 * Groups elements of the original collection by the key returned by the given [keySelector] function
 * applied to each element and returns a map where each group key is associated with a list of corresponding elements.
 *
 * The returned map preserves the entry iteration order of the keys produced from the original collection.
 * {false=[0, 1, 2, 3, 3, 2, 1, 0, -1], true=[4, 5, 4]}
 *
 * @sample samples.collections.Collections.Transformations.groupBy
 */
val groupBy=list.groupBy {value-> value>3 }

/**
 * 返回一個集合,通過 角標和值 來生成
 * Returns a list containing the results of applying the given [transform] function
 * to each element and its index in the original collection.
 * @param [transform] function that takes the index of an element and the element itself
 * and returns the result of the transform applied to the element.
 * [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1]
 */
val mapIndexed=list.mapIndexed { index, value ->value}

/**
 * 返回一個每一個非null元素根據給定的函數轉換所組成的List
 * Returns a list containing only the non-null results of applying the given [transform] function
 * to each element in the original collection.
 * [0, 2, 4, 6, 8, 10, 8, 6, 4, 2, 0, -2]
 */
val mapNotNull=list.mapNotNull { it*2 }

- 元素操作符

private val list= listOf(0,1,2,3,4,5,6,4,3,2,1,0,-1)

//如果指定元素可以在集合中找到,則返回true。
val contains=list.contains(2)

/**
 * 返回給定index對應的元素,如果index數組越界則會 拋出IndexOutOfBoundsException
 * Returns an element at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this collection.
 * 2
 */
val elementAt=list.elementAt(2)

/**
 * 返回給定index對應的元素,如果index數組越界則會根據給定函數返回默認值,第二個參數default,lamdba表達式
 * 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.
 * 2
 */
val elementAtOrElse=list.elementAtOrElse(2){"error"}

/**
 * 返回給定index對應的元素,如果index數組越界則會 返回null
 * Returns an element at the given [index] or `null` if the [index] is out of bounds of this list.
 * null
 */
val elementAtOrNull=list.elementAtOrNull(19)

/**
 * Returns first element.
 * @throws [NoSuchElementException] if the list is empty.
 * 0
 */
val first=list.first()

/**
 * 返回符合給定函數條件的第一個元素,沒有回拋異常
 * Returns the first element matching the given [predicate].
 * @throws [NoSuchElementException] if no such element is found.
 * 4
 */
val first2=list.first { it>3 }

/**
 * 返回符合給定函數條件的第一個元素,如果沒有符合則返回null
 * Returns the first element matching the given [predicate], or `null` if element was not found.
 * null
 */
val firstOrNull=list.firstOrNull { it>9 }

/**
 * 返回指定元素的第一個index,如果不存在,則返回-1
 * Returns the index of the first occurrence of the specified element in the list, or -1 if the specified
 * element is not contained in the list.
 * 3
 */
val indexOf=list.indexOf(3)

/**
 * 返回第一個符合給定函數條件的元素的index,如果沒有符合則返回-1
 * Returns index of the first element matching the given [predicate], or -1 if the list does not contain such element.
 * 0
 */
val indexOfFirst=list.indexOfFirst { it%3==0 }

/**
 * 返回最後一個符合給定函數條件的元素的index,如果沒有符合則返回-1
 * Returns index of the last element matching the given [predicate], or -1 if the list does not contain such element.
 * 11
 */
val indexOfLast=list.indexOfLast { it%3==0 }

/**
 * 返回符合給定函數條件的最後一個元素,沒有拋異常
 * Returns the last element matching the given [predicate].
 * @throws [NoSuchElementException] if no such element is found.
 * 6
 */
val last=list.last { it>4 }

/**
 * 返回指定元素的最後一個index,如果不存在,則返回-1
 * Returns the index of the last occurrence of the specified element in the list, or -1 if the specified
 * element is not contained in the list.
 * 8
 */
val lastIndexOf=list.lastIndexOf(3)

/**
 * 返回符合給定函數條件的最後一個元素,如果沒有符合則返回null
 * Returns the last element matching the given [predicate], or `null` if no such element was found.
 * null
 */
val lastOrNull=list.lastOrNull { it>8 }

/**
 * 返回符合給定函數的單個元素,如果沒有符合或者超過一個,則拋出異常
 * Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element.
 * 6
 */
val single=list.single { it>5 }

/**
 * 返回符合給定函數的單個元素,如果沒有符合或者超過一個,則返回null
 * Returns the single element matching the given [predicate], or `null` if element was not found or more than one element was found.
 * null
 */
val singleOrNull=list.singleOrNull { it>8 }

- 生產操作符

private val list1= listOf(0,1,2,3,4,5)
private val list2= listOf(4,5,2,1,5)

/**
 * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
 * [(0, 4), (1, 5), (2, 2), (3, 1), (4, 5)]
 */
val zip= list1.zip(list2)

/**
 * Returns a list of values built from elements of both collections with same indexes using provided [transform]. List has length of shortest collection.
 * [4, 6, 4, 4, 9]
 */
val zip2= list1.zip(list2){it1,it2->it1+it2}

//[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
val zip4= list1.zip(list1+list2)

//[0, 2, 4, 6, 8, 10]
val zip3= list1.zip(list1+list2){it1,it2->it1+it2}

/**
 * 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.
 * ([1, 3, 7], [3, 4, 8])
 */
val unzip= listOf(Pair(1,3),Pair(3,4),Pair(7,8)).unzip()

/**
 * 把一個給定的集合分割成兩個,第一個集合是由原集合每一項元素匹配給定函數條件返回true的元素組成,
 * 第二個集合是由原集合每一項元素匹配給定函數條件返回false的元素組成
 * 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`.
 * ([0, 2, 4], [1, 3, 5])  value
 */
val partition= list1.partition { it%2==0 }

/**
 * 返回一個包含原集合和給定集合中所有元素的集合,因爲函數的名字原因,我們可以使用+操作符。
 * Returns a list containing all elements of the original collection and then all elements of the given [elements] sequence.
 * [0, 1, 2, 3, 4, 5, 4, 5, 2, 1, 5]
 */
val plus=list1.plus(list2)

- 順序操作符

private val list= listOf(1,8,9,4,5,6,4,5,3,8,5)

/**
 * 返回一個與指定list相反順序的list
 * Returns a list with elements in reversed order.
 */
val reverse=list.reversed()

/**
 * 返回一個自然排序後的list
 * Returns a list of all elements sorted according to their natural sort order.
 */
val sort=list.sorted()

/**
 * 返回一個根據指定函數排序後的list
 * Returns a list of all elements sorted according to natural sort order of the value returned by specified [selector] function.
 */
val sortBy=list.sortedBy { it>3 }

/**
 * 返回一個降序排序後的List
 * Returns a list of all elements sorted descending according to their natural sort order.
 */
val sortDescending=list.sortedDescending()

/**
 * 返回一個根據指定函數降序排序後的list
 * Returns a list of all elements sorted descending according to natural sort order of the value returned by specified [selector] function.
 */
val sortDescendingBy=list.sortedByDescending { it>4 }

再來看看下面幾個更加常用和功能更加強大的操作符

data class Person(val name:String="wy",val age:Int=10)

//let

  fun function(){

      val  person=Person()

      person.let {
          person.name
          person.age
    }


    person.apply {
        name
        age
    }

    with(person){
        name
        age
    }

      with(person){
          person.apply {
              name
              age
          }
      }

      BufferedReader(FileReader("build.gradle")).use {

      }
}

以上幾個操作符我並不想做太多的解釋,相信如果你掌握了前面的幾類操作符之後,再查看這些操作符的源碼後肯定能快速掌握,畢竟這些真的不是什麼晦澀難懂的東西。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章