当前位置:嗨网首页>书籍在线阅读

09-标准高阶函数

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

11.2.2 标准高阶函数

Kotlin的标准库提供了一些常用的高阶函数,这些函数丰富了系统API,给开发者带来了极大的便利。

1.forEach

forEach函数通常用来遍历集合。代码如下。

val list = listOf(1, 2, 3, 4, 5)
list.forEach(::println)

2.map

map函数通常用于集合的映射,还可以用于集合的转换。代码如下。

val oldList = listOf(1, 2, 3, 4, 5)
    //map函数用于集合映射
    val newList = oldList.map {
        it * 2 + 3
    }
    println(newList)    //输出结果 [5, 7, 9, 11, 13]
    //map函数用于集合转换
    val new = oldList.map(Int::toDouble)    //输出结果[1.0, 2.0, 3.0, 4.0, 5.0]

3.flatMap

flatMap函数通常用于扁平化集合,就是把集合的集合再合并为集合。代码如下。

val list = listOf(
            1..20,
            2..5,
            3..4
    )
    val newList = list.flatMap {
        it
    }
    println(newList)
    //遍历集合
    newList.forEach(::println)

flatMap还可以结合map函数进行一些简单的变换操作。代码如下。

val list = listOf(
            1..20,
            2..5,
            3..4
    )
    val newList = list.flatMap {
        it.map {
            "NO.$it"
        }
    }
    println(newList)

4.reduce

reduce函数通常用于求和以及求阶乘操作。代码如下。

val oldList = listOf(1, 2, 3, 4, 5)
    var sum = oldList.reduce { acc, i -> acc + i }
    println(sum)   //输出15

5.filter

filter函数用于过滤,如果传入的表达式的值为true,则保留filter函数中的相关内容。代码如下。

val oldList = listOf(1, 2, 3, 4, 5)
    val newList = oldList.filter {
        it == 2 || it == 4
    }
    println(newList)   //输出[2, 4]

6.takeWhile

takeWhile函数通常用于带有条件的循环遍历。代码如下。

val oldList = listOf(1, 3, 2, 3, 4, 5)
    val res = oldList.takeWhile {
        it != 2
    }
    println(res)    //输出[1, 3]

在上面的代码中,当元素!=2时,则保留;当元素==2时,则结束循环。和takeWhile类似的是takeLastWhile,该函数从尾部开始进行倒序遍历。