字面量包括整形字面量、浮点数子面量、布尔型字面量、字符字面量、字符串字面量、符号字面量、函数字面量和元组字面量
除了函数字面量我们比较陌生以外,其他几种字面量都很容易理解
val counter: Int => Int = {(value) => value + 1}
val num1 = (num: Int) => num * 2
println(num1(1))
def main(args: Array[String]): Unit = {
var more = 1
val addMore = (x:Int) => x + more
print(addMore(10))
}
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)
}
val university = Map("XMU"->"Xiamen University","THU"->"Tsinghua University")
// filter操作可以实现过滤操作
val universityOfXiamen = university.filter({
kv => {
println(kv); // 这是一个map
kv._2 contains ("Xiamen") // 找到key中包含Xiamen的kv
}
})
print(universityOfXiamen)
// reduce 操作
val list = List(1,2,3,4,5)
val res1 = list.reduceLeft(_ + _) //从左往右
// 1+2 = 3; 3+3 = 6; 6+4=10;10+5 =15
val res2 = list.reduceRight(_ + _)
println(res1)
println(res2)
// 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.study
import java.io.File
import scala.io.Source
object WordCount {
def main(args: Array[String]): Unit = {
val dirfile = new File("./test")
val files = dirfile.listFiles()
for (file <- files) println(file)
val listFiles = files.toList
val 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)
}
}