Kotlin教程笔记(22) -常见高阶函数

简介: Kotlin教程笔记(22) -常见高阶函数

本系列学习教程笔记属于详细讲解Kotlin语法的教程,需要快速学习Kotlin语法的小伙伴可以查看“简洁” 系列的教程

快速入门请阅读如下简洁教程:
Kotlin学习教程(一)
Kotlin学习教程(二)
Kotlin学习教程(三)
Kotlin学习教程(四)
Kotlin学习教程(五)
Kotlin学习教程(六)
Kotlin学习教程(七)
Kotlin学习教程(八)
Kotlin学习教程(九)
Kotlin学习教程(十)

Kotlin教程笔记(22) -常见高阶函数

imgKotlin - 常见高阶函数

#forEach

高阶函数 forEach 是可迭代对象的扩展方法,接收函数类型是 (T) -> Unit 的参数 action,forEach 会将 action 这个函数作用于可迭代对象中的每个元素,这是源码:

/**
 * Performs the given [action] on each element.
 */
@kotlin.internal.HidesMembers
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

根据 forEach 的入参要求,我们给其传递一个 lambda 表达式或是函数引用:

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)
    // list.forEach { it -> println(it) } // it可以省略
    list.forEach { println(it) }
    list.forEach(::println)
    list.forEachIndexed { index, i -> println("index=$index, value=$i") }
}

forEachIndexed 相比 forEach 只是多了索引 index。

#map

高阶函数 map 也是可迭代对象的扩展方法,根据 map 的源码与注释,我们知道 map 接收一个类型是 (T) -> R 的参数 transform,map 会将 transform 作用于可迭代对象中的每个元素,并最终返回一个新的集合 List:

/**
 * 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> Iterable<T>.map(transform: (T) -> R): List<R> {
    return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}

借助 map 的功能,我们可以将一个数组 “映射” 成另一个数组,这在日常开发很有用:

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)

    // 将int数组中的元素经过某种运算形成一个新的int数组
    val newList = list.map { it * 2 + 3 }
    newList.forEach(::println)

    // 将int转成double
    val newList2 = list.map(Int::toDouble) // (Int) -> Double
    newList2.forEach(::println)
}

注意:toDouble()是 Int 类中的一个方法,在函数引用部分已经讲过,当使用 类名::方法名 这种方式引用一个成员方法时,会自动在函数类型的参数列表第 1 位多出一个接收者 Receiver,用于接收类实例对象 ,刚好 toDouble()没有参数列表,因此 Int::toDouble 对应的函数类型是 (Int) -> Double,符合高阶函数 map 的参数要求。

#flatMap

高阶函数 flatMapmap 高一个维度,可以将可迭代对象中的每个可迭代对象进行处理,最终返回一个 扁平化 的可迭代对象,注意参数 transform 的函数类型是 (T) -> Iterable<R>

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
 *
 * @sample samples.collections.Collections.Transformations.flatMap
 */
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

什么是 扁平化 ,直观的说,就是胖变瘦,多维变一维:

fun main(args: Array<String>) {
    val list = listOf(
        8..10,
        1..3,
        98..100
    )
    val flatList = list.flatMap { it } // it->it,这里同时也是 (Iterable) -> Iterable
    flatList.forEach(::println) // 这时的 flatList 就相当于 [8,9,10,1,2,3,98,99,100]
}

flatMap 除了 扁平化 这个特性外,也拥有 map 的特性,可以将可迭代对象中的元素进行转换处理:

fun main(args: Array<String>) {
    val list = listOf(
        8..10,
        1..3,
        98..100
    )
    val flatList2 = list.flatMap { intRange ->
        intRange.map { intElement -> "No. $intElement " } // 把Int转成String
    }
    flatList2.forEach(::print) // No. 8 No. 9 No. 10 No. 1 No. 2 No. 3 No. 98 No. 99 No. 100
}

#filter

高阶函数 filter 可以将可迭代对象进行过滤,只有满足 predicate 过滤条件的元素(即 return true)才会被 "留下":

/**
 * Returns a list containing only elements matching the given [predicate].
 *
 * @sample samples.collections.Collections.Filtering.filter
 */
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
    return filterTo(ArrayList<T>(), predicate)
}

我们可以使用 filter 过滤出数组中的奇数:

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)
    val newList = list.filter { it % 2 == 1 }
    newList.forEachIndexed { index, i -> print(if (index > 0) " $i" else i) } // 1 3 5 7
}

#takeWhile

高阶函数 takeWhile 会在遇到第一个不符合条件的元素时就结束取数据,留下前面的作为新的集合返回:

/**
 * Returns a list containing first elements satisfying the given [predicate].
 *
 * @sample samples.collections.Collections.Transformations.take
 */
public inline fun <T> Iterable<T>.takeWhile(predicate: (T) -> Boolean): List<T> {
    val list = ArrayList<T>()
    for (item in this) {
        if (!predicate(item))
            break
        list.add(item)
    }
    return list
}

我们可以使用 takeWhile 筛选出前面满足条件的元素:

fun main(args: Array<String>) {
    val list = listOf(1, 1, 2, 3, 5, 8, 13, 21)

    var newList = list.takeWhile { it % 2 == 1 } // 筛选出前面的奇数
    newList.forEachIndexed { index, i -> print(if (index > 0) " $i" else i) } // 1 1

    newList = list.takeWhile { it < 5 } // 筛选出前面小于5的数
    newList.forEachIndexed { index, i -> print(if (index > 0) " $i" else i) } // 1 1 2 3
}

#reduce

高阶函数 reduce 会从第一个元素开始累加,并从左到右将 operation 函数应用于当前累加值和每个元素:

/**
 * Accumulates value starting with the first element and applying [operation] from left to right to current accumulator value and each element.
 *
 * @sample samples.collections.Collections.Aggregates.reduce
 */
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
}

我们可以用 reduce 来处理一些累加的操作,如计算 1 到 8 之间所有的数进行求和:

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)
    val result = list.reduce { acc, i -> acc + i }
    println(result) // 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
}

#fold

高阶函数 foldreduce 差不多,只是 fold 多了一个初始值,后续处理与 reduce 一样:

/**
 * Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each element.
 */
public inline fun <T, R> Iterable<T>.fold(initial: R, operation: (acc: R, T) -> R): R {
    var accumulator = initial
    for (element in this) accumulator = operation(accumulator, element)
    return accumulator
}

我们可以 fold 来计算在 100 的基础上,再累加 1 到 8 的和:

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)
    val result = list.fold(100, { acc, i -> acc + i })
    println(result) // 100 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 37
}
相关文章
|
2天前
|
编解码 Java 程序员
写代码还有专业的编程显示器?
写代码已经十个年头了, 一直都是习惯直接用一台Mac电脑写代码 偶尔接一个显示器, 但是可能因为公司配的显示器不怎么样, 还要接转接头 搞得桌面杂乱无章,分辨率也低,感觉屏幕还是Mac自带的看着舒服
|
3天前
|
存储 缓存 关系型数据库
MySQL事务日志-Redo Log工作原理分析
事务的隔离性和原子性分别通过锁和事务日志实现,而持久性则依赖于事务日志中的`Redo Log`。在MySQL中,`Redo Log`确保已提交事务的数据能持久保存,即使系统崩溃也能通过重做日志恢复数据。其工作原理是记录数据在内存中的更改,待事务提交时写入磁盘。此外,`Redo Log`采用简单的物理日志格式和高效的顺序IO,确保快速提交。通过不同的落盘策略,可在性能和安全性之间做出权衡。
1540 5
|
1月前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
7天前
|
人工智能 Rust Java
10月更文挑战赛火热启动,坚持热爱坚持创作!
开发者社区10月更文挑战,寻找热爱技术内容创作的你,欢迎来创作!
578 22
|
3天前
|
存储 SQL 关系型数据库
彻底搞懂InnoDB的MVCC多版本并发控制
本文详细介绍了InnoDB存储引擎中的两种并发控制方法:MVCC(多版本并发控制)和LBCC(基于锁的并发控制)。MVCC通过记录版本信息和使用快照读取机制,实现了高并发下的读写操作,而LBCC则通过加锁机制控制并发访问。文章深入探讨了MVCC的工作原理,包括插入、删除、修改流程及查询过程中的快照读取机制。通过多个案例演示了不同隔离级别下MVCC的具体表现,并解释了事务ID的分配和管理方式。最后,对比了四种隔离级别的性能特点,帮助读者理解如何根据具体需求选择合适的隔离级别以优化数据库性能。
201 3
|
10天前
|
JSON 自然语言处理 数据管理
阿里云百炼产品月刊【2024年9月】
阿里云百炼产品月刊【2024年9月】,涵盖本月产品和功能发布、活动,应用实践等内容,帮助您快速了解阿里云百炼产品的最新动态。
阿里云百炼产品月刊【2024年9月】
|
10天前
|
Linux 虚拟化 开发者
一键将CentOs的yum源更换为国内阿里yum源
一键将CentOs的yum源更换为国内阿里yum源
578 5
|
23天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。
|
6天前
|
XML 安全 Java
【Maven】依赖管理,Maven仓库,Maven核心功能
【Maven】依赖管理,Maven仓库,Maven核心功能
233 3
|
9天前
|
存储 人工智能 搜索推荐
数据治理,是时候打破刻板印象了
瓴羊智能数据建设与治理产品Datapin全面升级,可演进扩展的数据架构体系为企业数据治理预留发展空间,推出敏捷版用以解决企业数据量不大但需构建数据的场景问题,基于大模型打造的DataAgent更是为企业用好数据资产提供了便利。
327 2