{ } 为结构体,最后一个表达式的结果为变量的值
定义方法
def m1(a:Int,b:Int):Int=a*b 返回值类型可以省略不写
定义函数
val f1=(x:Int,y:Int)=>{x+y}
还可以这样写
val func:Int=>String={x=>x.toString}
val func2:(Int,Double)=>(Double,Int)={(x,y)=>(y,x)} 传入多个值 需要用括号扩起来,类似与python 元组
函数名:参数类型=> 返回值类型={} x 代表传入的参数
scala 难就难在太灵活,可以有多种不同的写法
函数和方法的区别最大的区别是,函数可以作为一个变量 传入一个方法内
val arr=1 to 10
arr.map(_*10)=arr.map((x:Int)=>{x*10}) _代表每一个元素
相当与传入一个匿名函数 因为arr装的为Int还可以简化为
r.map(x=>x*10) 神奇的下划线
神奇的下划线,可以将 方法装换成函数
def m1(x:Int,y:Int):Int={x+y}
val f1=m1 _ 直接后面跟下划线即可
object 伴生对象,类似与java static
推荐使用val 不可变
val arr =new Array[Int](10) 申请10个地址 全为Int 默认值 0 长度为10
val arr =Array(10) 默认初始值 为10 长度为1
也可不new 会默认调用 object 里面的apply 方法apply 方法封装了new
会自动调用相应参数的apply方法
import ascala.collection.mutable.ArrayBuffer mutable可变的
val ab=ArrayBuffer[Int](10) ArrayBuffer 变长
追加array ++=
Any 超类类似与 java object
0 until 从零开始 前闭后开 reverse 反转
for (i <- arr) yield i*3 返回一个新的数组
val m=Map("a"->1,"b"->2) 默认为Imutable 不可变 Map
val m=Map(("a",1),("b",2))
import scala.collection.mutable.Map 导入可变的Map
m.getorelse("c",0) 返回默认值 其实是 option some
元组 tuple ,可以放多种类型的元素
val t=(1,"test",3.6) 角标从1开始
访问 t._1 t._2 t._3
val t,(x,y,z)=("a",2.4,1)
就可以直接 x y z 代表 a 2.4 1
拉链操作
val a=Array("a","b","c")
val b=Array(1,2,3)
a.zip(b)
res19: Array[(String, Int)] = Array((a,1), (b,2), (c,3))
res19.toMap
拉链多余的将会被舍弃
scala 集合三大类 序列 Seq 集 Set ,映射Map 扩展自 Iterable
val list=List(1,2,3)
import scala._ _与java * 相同
val lst=List(1,8,3,7,2,6,4)
lst.sorted
lst.grouped(4) 4 element a group
val lst2=lst.grouped(5).toList
lst2: List[List[Int]] = List(List(1, 3, 7, 2, 9), List(5))
list include list
so flatten yaping
lst2: List[List[Int]] = List(List(1, 3, 7, 2, 9), List(5))
lst2.flatten
res7: List[Int] = List(1, 3, 7, 2, 9, 5)
single machine WordCount:
val lines=List("hello tom hello jerry","hello jerry","hello kitty")
sc.textFile("/home/h").flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).sortBy(_._2,false).take(10)
lines.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).map(t=>(t._1,t._2.size)).toList.sortBy(_._2).reverse
lines.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).mapValues(_.size)
lines.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2))
sparkContext first split
flatMap= map flatten
source.formFile("")
hello -> List((hello,1), (hello,1), (hello,1), (hello,1)) a tuple
key is hello value is a List List include four tuple
_ represent any one
map(_,_1,_._2.size) not allow must be map(t=>(t._1,t._2.size)) anonymous function like this
or diect process the tuple value mapValue()
lines.flatMap(_.split(" ")).map((_,1)).groupBy(_._1)
res22: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(tom -> List((tom,1)), kitty -> List((kitty,1)), jerry -> List((jerry,1), (jerry,1)), hello -> List((hello,1), (hello,1), (hello,1), (hello,1)))
lines.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2))
mapValues(_.foldLeft(0)(_+_._2))
1 _ List((hello,1), (hello,1), (hello,1), (hello,1))
2 _ fold init value 0 or las