大數據系列修煉-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
實例程序:
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
}