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

 

相关文章:

  • 2022-03-10
  • 2021-08-30
  • 2021-12-20
  • 2022-12-23
  • 2021-10-26
  • 2022-03-04
  • 2021-05-22
  • 2022-01-21
猜你喜欢
  • 2021-09-02
  • 2022-12-23
  • 2021-10-03
  • 2021-06-07
  • 2022-12-23
  • 2022-12-23
  • 2021-07-08
相关资源
相似解决方案