scala高阶函数练习
1、获取元素中每个元素的长度
val datas = Array(“spark”,“hello”,“scala”,“python”)
object Test01 {
def main(args: Array[String]): Unit = {
val datas = Array("spark","hello","scala","python")
val func = (x:String) => x.length
println(testOne(datas,func).toList)
//函数简写规则
//1、直接将函数值传递进去
println(testOne(datas,(x:String) => x.length).toList)
//2、省略函数参数类型(在定义testOne方法时已经给出函数类型)
println(testOne(datas,(x) => x.length).toList)
//3、函数只有一个参数时,()可以省略
println(testOne(datas,x => x.length).toList)
//4、函数参数只使用了一次,且没有嵌套使用,此时参数可以用_代替
//下面是函数简写完的样子
println(testOne(datas, _.length).toList)
}
def testOne(datas:Array[String],func:(String => Any)) = {
for (element<- datas) yield {
func(element)
}
}
}
2、对数组中的数据进行过滤
val datas = Array(1,4,6,8,10,3,5)
object Test02 {
def main(args: Array[String]): Unit = {
val datas = Array(1,4,6,8,10,3,5)
println(testTwo(datas, _ % 2 == 0).toList)
}
def testTwo(datas:Array[Int],func:(Int=>Boolean))={
for (element<- datas if(func(element))) yield {
element
}
}
}
3、根据指定规则获取数组中的最大元素
val datas = Array(“zhangsan 20 2500”,“lisi 30 5000”,“zhaoliu 25 3500”)
object Test03 {
def main(args: Array[String]): Unit = {
val datas = Array("zhangsan 20 2500","lisi 30 5000","zhaoliu 25 3500")
println(testThree(datas, _.split(" ")(2).toInt))
}
def testThree(datas:Array[String],func:(String => Int))={
var tmp = datas(0)
for (element<-datas) {
if(func(tmp) < func(element)){
tmp = element
}
}
tmp
}
}
4、根据指定规则对数据进行分组
val datas = Array(“zhangsan 男 shenzhen”,“lisi 女 beijing”,“zhaoliu 男 beijing”)
object Test04 {
def main(args: Array[String]): Unit = {
val datas = Array("zhangsan 男 shenzhen","lisi 女 beijing","zhaoliu 男 beijing")
println(testFour(datas,_.split(" ")(1)))
}
def testFour(datas:Array[String],func:(String=>String))={
val map = new util.HashMap[String, util.List[String]]()
for (element<- datas) {
val key = func(element)
if(map.containsKey(key)) {
val list = map.get(key)
list.add(element)
}else{
val list = new util.ArrayList[String]()
list.add(element)
map.put(key,list)
}
}
map
}
}
5、对数据进行聚合
val datas = Array(1,2,3,4,5,6,7,8,8)
object Test05 {
def main(args: Array[String]): Unit = {
val datas = Array(1,2,3,4,5,6,7,8,8)
println(agg(datas, _ + _))//对加号进行修改可以改变数据聚合的规则
}
def agg(datas:Array[Int],func:(Int,Int)=>Int) = {
var tmp = datas(0)
for (element <- 1 until datas.length) {
tmp = func(tmp,datas(element))
}
tmp
}
}