kotlin集合操作-高阶函数reduce和fold

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 时,操作参数会更改其顺序:第一个参数变为元素,然后第二个参数变为累积值。

原文地址:https://www.cnblogs.com/huyang011/p/14653241.html