大數據系列修煉-Scala課程35
核心內容:
1、scala中List的map、flatMap、foreach、filter操作代碼實戰
1、Scala中List的map、flatMap、foreach、filter操作代碼實戰 |
1>map就是對集合中的所有元素履行1個具體的函數,將函數作用在數值上,并返回1個新的集合結果
2>flatMap:首先對List內部的每一個成員進行map操作,map產生的結果會是1個List(List(char)),然后在產生結果的基礎上
進行flat–將map操作后的結果進行合并,產生合并以后的集合(List[char])。
簡單來講:flatMap首先履行map操作,然后對產生集合的結果進行合并,合并出1個新的集合結果
toList作用在具體的字符串上面:將字符串的list集合變成字符的list集合:List[List[Char]]
3>foreach:就是對集合中的每個元素履行1個具體的函數,將函數作用在數值上,與map不同的是,foreach不產生具體的
結果,結果是Unit類型的。
4>filter:過濾出列表中符合條件的元素,filter結構中傳進來的參數是1個結構為布爾類型的函數。
實例程序1:
//map函數:就是對集合中的所有元素履行1個具體的函數,將函數作用在數值上,并產生1個新的集合結果
val arr = Array(10,20,30) //> arr : Array[Int] = Array(10, 20, 30)
val arr2 = arr.map((x:Int)=>x+100) //> arr2 : Array[Int] = Array(110, 120, 130)
//將List集合中的每個元素加10,并返回1個新的集合結果
val list1 = List(10,20,30,40) //> list1 : List[Int] = List(10, 20, 30, 40)
list1.map((x:Int)=>x+10) //> res0: List[Int] = List(20, 30, 40, 50)
list1.map((x)=>x+10) //> res1: List[Int] = List(20, 30, 40, 50)
list1.map(_+10) //> res2: List[Int] = List(20, 30, 40, 50)
val data = List("Scala","Hadoop","Spark") //> data : List[String] = List(Scala, Hadoop, Spark)
data.toList //> res3: List[String] = List(Scala, Hadoop, Spark)
data.toList.reverse //> res4: List[String] = List(Spark, Hadoop, Scala)
//toList作用在具體的字符串上面:將字符串的list集合變成字符的list集合:List[List[Char]]
data.map(_.toList) //> res5: List[List[Char]] = List(List(S, c, a, l, a), List(H, a, d, o, o, p), L
//| ist(S, p, a, r, k))
data.flatMap(_.toList) //> res6: List[Char] = List(S, c, a, l, a, H, a, d, o, o, p, S, p, a, r, k)
data.map(_.toList.reverse.mkString("\t")) //> res7: List[String] = List(a l a c S, p o o
//| d a H, k r a p S)
//將List集合變成1個字符串
data.toList.reverse.mkString("---") //> res8: String = Spark---Hadoop---Scala
data.map((str:String)=>str.length) //> res9: List[Int] = List(5, 6, 5)
data.map(_.length) //> res10: List[Int] = List(5, 6, 5)
data.map(_.toList.reverse.mkString) //> res11: List[String] = List(alacS, poodaH, krapS)
實例程序2:
object App
{
def main(args:Array[String]):Unit=
{
val list = List(10,20,30,40)
val list2 = list.foreach((x:Int)=>x+10)
val list3 = list.map((x:Int)=>x+10)
println(list2)
println(list3)
var sum = 0
list.foreach(sum+=_)
println(sum)
val list4 = List.range(1, 11).filter(_%2==0)
println(list4)
val list5 = List("spark","hadoop","hbase").filter(_.length==5)
println(list5)
}
}
運行結果:
()
List(20, 30, 40, 50)
100
List(2, 4, 6, 8, 10)
List(spark, hbase)