1、定义一个高阶函数,按照指定的规则对集合里面的每个元素进行操作
比如: Array(“hh”,“red”,“java”,“hadoop”)
object p2 {
def main(args: Array[String]): Unit = {
val list = Array("spark", "hello", "java", "hadoop")
val fun = (s: String) => {
s.length
}
println(doSome(list, fun))
println(doSome(list, (s: String) => {
s.length
}))
println(doSome(list,(s)=>s.length))
println(doSome(list,s=>s.length))
println(doSome(list,_.length))
}
def doSome(list: Array[String], fun: (String) => Int) = {
val res = for (elem <- list) yield {
fun(elem)
}
res.toList
}
}
规则: 对集合中每个元素进行操作,得到集合每个元素的长度
2、定义一个高阶函数,对数据中的元素按照指定的规则进行过滤
比如: Array(1,4,7,9,10,6,8,99,88,66)
规则: 只保留偶数数据
object p3 {
def main(args: Array[String]): Unit = {
val list = Array(1,4,7,9,10,6,8,99,88,66)
println(filter(list,(_%2==0)))
}
def filter(list: Array[Int],fun:(Int)=>Boolean) = {
//用fun做守卫,过滤
val res = for (elem <- list if (fun(elem))) yield {
elem
}
res.toList
}
}
3、对数据中的元素按照指定规则进行分组
比如:Array(“zhangsan shenzhen man”,“lisi beijing woman”,“zhaoliu beijing man”)
规则: 按照地址进行分组
object p4{
def main(args: Array[String]): Unit = {
val list = Array("zhangsan shenzhen man","lisi beijing woman","zhaoliu beijing man")
println(group(list,_.split(" ")(2)))
}
def group(list:Array[String],fun:(String)=>String) = {
val map = new util.HashMap[String,util.ArrayList[String]]()
for (elem <- list) {
val key = fun(elem)
if(map.containsKey(key)){
map.get(key).add(elem)
}else{
val value = new util.ArrayList[String]()
value.add(elem)
map.put(key,value)
}
}
map
}
}
4、根据指定规则对数组所有元素聚合
比如:Array(10,4,6,10,2)
规则: 求和/求乘积
object p5 {
def main(args: Array[String]): Unit = {
val list = Array(10,4,6,10,2)
println(poly(list,_+_))
}
def poly(list:Array[Int],fun:(Int,Int)=>Int) = {
var res = list(0)
for (i<-1 until list.size) res = fun(res,list(i))
res
}
}