求字符串中单词出现次数val arr = Array(“hello tom”,“hello jerry”,“hello hello”)
//1.先将每一个字符串分割
var f4 = (x:String)=>x.split("\\s")
//2.分割出的结果为Array(Array(hello,tom),Array(hello,jerry),Array(hello,hello))
var arr1 = arr.map(f4)
//3.将数组平铺
var f5 = (x:Array[String]) => List(x(0),x(1))
//4.平铺的结果为List(hello,tom,hello,jerry,hello,hello)
var arr2 = arr1.flatMap(f5)
//5.将集合中的每一个元素转换格式
//6.转换结果为
// List((hello,1),(tom,1),(hello,1),(jerry,1),(hello,1),(hello,1))
var arr3 = arr2.map(x=>(x,1))
//7.将集合中的元组分组,结果为
//Map(tom -> [Lscala.Tuple2;@62ee68d8, jerry -> [Lscala.Tuple2;@735b5592, hello -> [Lscala.Tuple2;@58651fd0)
//Map(tom -> ((tom,1)), jerry -> ((jerry,1)), hello -> ((hello,1),(hello,1),(hello,1),(hello,1)))
var arr4 = arr3.groupBy(_._1)
println(arr4)
//8.显示最终结果
var arr5 = arr4.map(x=>(x._1,x._2.length))
println(arr5)