reduce函數
作用: 將所提供的操作應用於集合元素並返回累積的結果
reduce函數定義如下:
/** * Accumulates value starting with the first element and applying [operation] from left to right to current accumulator value and each element. */ public inline fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S { val iterator = this.iterator() if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.") var accumulator: S = iterator.next() while (iterator.hasNext()) { accumulator = operation(accumulator, iterator.next()) } return accumulator }
此函數定義了兩個泛型S,以及S的子類T, 返回值是S類型。
此擴展函數的參數是函數類型,此函數有兩個參數: 先前的累積值(acc)和集合元素
舉例:
val listReduce :String = listOf("hello", "1", "2", "3", "4").reduce { acc, str ->
acc + str
}
返回結果就是字符串: hello1234
fold函數
作用: 將所提供的操作應用於集合元素並返回累積的結果
與reduce函數的區別是:
fold()
接受一個初始值並將其用作第一步的累積值,
而 reduce()
的第一步則將第一個和第二個元素作為第一步的操作參數
val listFold :String = listOf("hello", "1", "2", "3", "4").fold("初始值") { acc, nextElement -> acc + nextElement }
返回結果就是字符串:初始值hello1234
函數 reduceRight() 和 foldRight() 它們的工作方式類似於 fold() 和 reduce(),但從最后一個元素開始,然后再繼續到前一個元素。
記住,在使用 foldRight 或 reduceRight 時,操作參數會更改其順序:第一個參數變為元素,然后第二個參數變為累積值。