scala高階函式--flatmap和reduce
阿新 • • 發佈:2021-08-17
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