scala> var list=Array("this is a demo","hello word")
list: Array[String] = Array(this is a demo, hello word)
scala> list.map(line=>line.split(" ")) // 等价list.map(_.split(" "))
res13: Array[Array[String]] = Array(Array(this, is, a, demo), Array(hello, word))
flatMap
scala> var list=Array("this is a demo","hello word")
list: Array[String] = Array(this is a demo, hello word)
scala> list.flatMap(_.split(" "))
res16: Array[String] = Array(this, is, a, demo, hello, word)
scala> list.flatMap(_.split(" ")).map((_,1))
res17: Array[(String, Int)] = Array((this,1), (is,1), (a,1), (demo,1), (hello,1)
, (word,1))
scala> list.flatMap(line=> (for(i<-line.split(" ")) yield (i,1)))
res20: Array[(String, Int)] = Array((this,1), (is,1), (a,1), (demo,1), (hello,1)
, (word,1))
filter/filterNot
scala> var list=Array("this is a demo","hello word")
list: Array[String] = Array(this is a demo, hello word)
scala> list.filter(line=>line.contains("hello"))
res24: Array[String] = Array(hello word)
scala> list.filterNot(line=>line.contains("hello"))
res25: Array[String] = Array(this is a demo)
var arrs=Array("this is a demo","good good study","day day up")
arrs.flatMap(_.split(" "))
.groupBy(word=>word)
.toList
.map(tuple=>(tuple._1,tuple._2.size))
.sortBy(_._1)
.foreach(println)
元组计算
var arrs=Array("this is a demo","good good study","day day up")
arrs.flatMap(_.split(" "))
.map((_, 1))
.groupBy(_._1)
.toList
.map(t=>(t._1,t._2.map(_._2).sum))
.sortBy(_._2)
.foreach(println)