大数据学习——scala的wordCount小例子

    val lines=List("hello tom hello jerry","hello tom hello kitty hello china")
    //方法一:
    val wc=lines.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).map(t=>(t._1,t._2.size)).toList.sortBy(_._2).reverse
    //方法二:
    val wc2=lines.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).mapValues(_.size)
    //方法三:
    val wc3=lines.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2))
    //如果是在spark上:
//    val wc4=lines.flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).sortBy(_._2,false).collect

 

posted on 2019-06-02 18:58  o_0的园子  阅读(520)  评论(0编辑  收藏  举报