Scala入门学习之【wordcount】

来源:互联网 发布:php .net哪个好学 编辑:程序博客网 时间:2024/06/08 03:19
[plain] view plain copy
  1. val lines = List("hello tom hello jerry", "hello jerry", "hello kitty")  
  2.   
  3.    println(lines.flatMap(_.split(" ")))  
  4.    //List(hello, tom, hello, jerry, hello, jerry, hello, kitty)  
  5.    //flatMap中的_表示一行内容 hello tom hello jerry  一共有三行  即对每行操作  
  6.    //flatMap(_.split(" ")) 中的_.split(" ") 就相当于"hello tom hello jerry".split(" ")  
  7.   
  8.   
  9.    println(lines.flatMap(_.split(" ")).map((_ ,1)))  
  10.    //List((hello,1), (tom,1), (hello,1), (jerry,1), (hello,1), (jerry,1), (hello,1), (kitty,1))  
  11.    //返回的List集合,集合里边每一个元素为元组  访问元组的第一个元素为_._1  
  12.    //例如:println((""hello",1)._1)  结果为hello  
  13.    //lines.flatMap(_.split(" ")).map((_ ,1))中的map((_ ,1) _表示每一个单词,1表示每出现一次计数为1  
  14.   
  15.   
  16.   
  17.    println(lines.flatMap(_.split(" ")).map((_ ,1)).groupBy(_._1))  
  18.    //Map(tom -> List((tom,1)), kitty -> List((kitty,1)), jerry -> List((jerry,1), (jerry,1)), hello -> List((hello,1), (hello,1), (hello,1), (hello,1)))  
  19.   // lines.flatMap(_.split(" ")).map((_ ,1)).groupBy(_._1)中的groupBy(_._1)表示按照list中每个元组中的第一个字段分组即拿第一个字段作为key,返回结果是一个大Map  
  20.    //groupBy(_._1)中的第一个_表示list中的每一个元组,而  ._1  表示取每一个元组中的第一个元素  
  21.   
  22.   
  23.   
  24.   
  25.    println(lines.flatMap(_.split(" ")).map((_ ,1)).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2)))  
  26.    //Map(tom -> 1, kitty -> 1, jerry -> 2, hello -> 4)  
  27.   // lines.flatMap(_.split(" ")).map((_ ,1)).groupBy(_._1).mapValues()中的mapValues()仅仅会对value处理,处理完了把key 结合起来  
  28.    //  mapValues()中的第一个_表示map里边的value ,而value是一个list  
  29.    //lines.flatMap(_.split(" ")).map((_ ,1)).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2))  中的foldLeft(0)是给一个初始值  
  30.     // (_+_._2)中的第一个_表示初始值或者累加过的值,第二个_表示List里边的元组,._2表示拿到元组中的第二个字段  
  31.   
  32.   
  33.   
  34.   
  35.    println(lines.flatMap(_.split(" ")).map((_ ,1)).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2)).toList)  
  36.   // List((tom,1), (kitty,1), (jerry,2), (hello,4))  
  37.    // 转化为List  
  38.   
  39.   
  40.   
  41.    println(lines.flatMap(_.split(" ")).map((_ ,1)).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2)).toList.sortBy(_._2))  
  42.  //List((tom,1), (kitty,1), (jerry,2), (hello,4))  
  43.    //sortBy(_._2)中的第一个_ 表示每一个元组,第二个._2 每个元组中的第二个字段  
  44.   
  45.   
  46.   
  47.    println(lines.flatMap(_.split(" ")).map((_ ,1)).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2)).toList.sortBy(_._2).reverse)  
  48.    //List((hello,4), (jerry,2), (kitty,1), (tom,1))  
  49.    //reverse表示降序排序  
原创粉丝点击