国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php框架 > 框架设计 > 大数据系列修炼-Scala课程36

大数据系列修炼-Scala课程36

来源:程序员人生   发布时间:2016-09-27 09:20:49 阅读次数:2832次

大数据系列修炼-Scala课程36


核心内容:
1、List的partition、find、takeWhile、dropWhile、span、forall、exsists操作代码实战


1、List的partition、find、takeWhile、dropWhile、span、forall、exsists操作代码实战

List中经常使用的方法:
partition:对集合中的元素依照某种条件进行分区
span:span的操作类似与partition,将集合分成不同的区域
find:找出集合中第1个满足条件的元素,返回值为Some或None
takeWhile:获得集合当中所有满足条件的元素
dropWhile:获得集合当中满足条件之外的元素
forall:只有集合当中的所有元素都满足条件时才返回true,否则返回false

exists:只要集合当中存在1个元素满足条件就返回true

实例程序:

object App68 { val list = List(1,2,3,4,5) //> list : List[Int] = List(1, 2, 3, 4, 5) list.partition(_%2==0) //> res0: (List[Int], List[Int]) = (List(2, 4),List(1, 3, 5)) //partition默许是将数据分成两个区 val (a,b) = list.partition(_%2==0) //> a : List[Int] = List(2, 4) //| b : List[Int] = List(1, 3, 5) //span的操作类似与partition的分区操作 println(list.span((x:Int)=>x<4)) //> (List(1, 2, 3),List(4, 5)) //find找出集合当中第1个满足条件的元素 val list2 = List(-2,0,1,2,3,4,5) //> list2 : List[Int] = List(-2, 0, 1, 2, 3, 4, 5) list2.find((x:Int)=>x % 4 == 0) //> res1: Option[Int] = Some(0) list2.find((x:Int)=> x < 4) //> res2: Option[Int] = Some(-2) list2.find(_ == 5) //> res3: Option[Int] = Some(5) list2.find(_ == 10) //> res4: Option[Int] = None //takeWhile获得集合中所有满足条件的的元素 list2.takeWhile((x:Int)=>x<4) //> res5: List[Int] = List(-2, 0, 1, 2, 3) list2.takeWhile(_<4) //> res6: List[Int] = List(-2, 0, 1, 2, 3) //dropWhile获得集合中满足条件之外的元素 list2.dropWhile(_<4) //> res7: List[Int] = List(4, 5) //判读在1个矩阵中是不是存在某1行元素,这1行的元素全部为0 def fun(m:List[List[Int]]) = m.exists(_.forall(_==0)) //> fun: (m: List[List[Int]])Boolean val m1 = List(List(10,20,30),List(40,50,60),List(0,0,0)) //> m1 : List[List[Int]] = List(List(10, 20, 30), List(40, 50, 60), List(0, 0, //| 0)) val m2 = List(List(10,20,30),List(40,50,60),List(10,0,0)) //> m2 : List[List[Int]] = List(List(10, 20, 30), List(40, 50, 60), List(10, 0, //| 0)) println(fun(m1)) //> true println(fun(m2)) //> false def fun1(m:List[Int]) = m.exists((x:Int)=>x>0)//> fun1: (m: List[Int])Boolean def fun2(m:List[Int]) = m.forall((x:Int)=>x>0)//> fun2: (m: List[Int])Boolean println(fun1(List(10,20,30,-10))) //> true println(fun2(List(10,20,30,-10))) //> false }
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生