scala高阶函数--flatmap和reduce

 

flatmap: 将一个元素拆分成多个元素

reduce: 聚合函数

package day3

object demo_high_func {
    def main(args: Array[String]): Unit = {
        val list = Array(1,2,3,4,5,6,7,7,7,8)
        // 过滤数组中的元素, 将为true的元素组合成一个新的数组
        val list2 = list.filter(e=>e%2==0)
        println(list2.mkString("[",",","]"))

        // map函数,对每个元素操作
        println("-" * 40 + "map" + "-" * 40)
        val list3 = list.map(n=>n * 10)
        println(list3.mkString("[",",","]"))

        println("-" * 40 + "flatMap" + "-" * 40)
        val words = Array("hello you", "hello me", "hello other")
        val flist = words.flatMap(word=>word.split(" "))
        println(flist.mkString("[",",","]"))

        println("-" * 40 + "reduce" + "-" * 40)
        //聚合函数, 啥意思看打印结果吧
        val relist = list.reduce((a1,a2)=>{
            println("v1= " + a1 + ",v2=" +a2)
            a1 + a2
        })
        // 普通写法
        val res = list.reduce((v1,v2)=>v1+v2)
        //简单写法
        val res1 =  list.reduce(_ + _)
        println(res)
        println(res1)
    }

}

打印结果:

[2,4,6,8]
----------------------------------------map----------------------------------------
[10,20,30,40,50,60,70,70,70,80]
----------------------------------------flatMap----------------------------------------
[hello,you,hello,me,hello,other]
----------------------------------------reduce----------------------------------------
v1= 1,v2=2
v1= 3,v2=3
v1= 6,v2=4
v1= 10,v2=5
v1= 15,v2=6
v1= 21,v2=7
v1= 28,v2=7
v1= 35,v2=7
v1= 42,v2=8
50
50

posted on 2021-08-17 22:29  孔扎根  阅读(320)  评论(0编辑  收藏  举报

导航