函数字面量
字面量包括整形字面量、浮点数子面量、布尔型字面量、字符字面量、字符串字面量、符号字面量、函数字面量和元组字面量
除了函数字面量我们比较陌生以外,其他几种字面量都很容易理解
val counter: Int => Int = {(value) => value + 1}
匿名函数
val num1 = (num: Int) => num * 2println(num1(1))
闭包
def main(args: Array[String]): Unit = {var more = 1val addMore = (x:Int) => x + moreprint(addMore(10))}
map操作和flatMap操作
def main(args: Array[String]): Unit = {// map操作 flatMap操作val books = List("Hadoop","Hive","HDFS")print(books.map(s => s.toUpperCase) + "\n")println(books)// flatMap是map的一种扩展,在flatMap中,我们会传入一个函数,// 该函数的对每个输入都会返回一个集合(而不是一个元素)// 然后 flatMap把生成的多个集合 “拍扁”成为一个集合println(books.flatMap(s => s.toUpperCase)) //List(H, A, D, O, O, P, H, I, V, E, H, D, F, S)}
filter操作
val university = Map("XMU"->"Xiamen University","THU"->"Tsinghua University")// filter操作可以实现过滤操作val universityOfXiamen = university.filter({kv => {println(kv); // 这是一个mapkv._2 contains ("Xiamen") // 找到key中包含Xiamen的kv}})print(universityOfXiamen)
reduce操作
// reduce 操作val list = List(1,2,3,4,5)val res1 = list.reduceLeft(_ + _) //从左往右// 1+2 = 3; 3+3 = 6; 6+4=10;10+5 =15val res2 = list.reduceRight(_ + _)println(res1)println(res2)
fold操作
// fold操作val list = List(1,2,3,4,5)print(list.fold(10)(_*_))// 10*1 =10;10*2=20 .... 240*5 = 1200
函数式编程实例
package com.test.studyimport java.io.File
import scala.io.Sourceobject WordCount {def main(args: Array[String]): Unit = {val dirfile = new File("./test")val files = dirfile.listFiles()for (file <- files) println(file)val listFiles = files.toListval wordMap = scala.collection.mutable.Map[String,Int]()listFiles.foreach( file => Source.fromFile(file).getLines().foreach(line => line.split(" ").foreach(word => {if (wordMap.contains(word)) {wordMap(word) += 1} else {wordMap += (word -> 1)}})))for((key,value) <- wordMap) println(key+":"+value)}
}