使用IDEA scala实现wordcount

object WordCount {
  def main(args: Array[String]): Unit = {
    val list=List("hello scala java","hello mysql scala","hello oracel","hello javaee")

    //读出每一个单词  List(hello, scala, java, hello, mysql, scala, hello, oracel, hello, javaee)
    val words: List[String] = list.flatMap(_.split(" "))
    
    //每一个元素变成List((hello,1), (scala,1), (java,1), (hello,1), (mysql,1), (scala,1), (hello,1), (oracel,1), (hello,1), (javaee,1))
    val wordOne: List[(String, Int)] = words.map((_,1))
    
    //根据元素分类  五个键值对
    // HashMap(javaee -> List((javaee,1)), java -> List((java,1)), oracel -> List((oracel,1)), scala -> List((scala,1), (scala,1)), mysql -> List((mysql,1)), hello -> List((hello,1), (hello,1), (hello,1), (hello,1)))
    val groupWords: Map[String, List[(String, Int)]] = wordOne.groupBy(_._1)
    //   f代表键值对   java -> List((java,1))
    val result=groupWords.map(f=>{
    //f._2   List((java,1))
      val list:List[(String,Int)]=f._2
      val nums:List[Int]=list.map(_._2)
      //求和
      val counts=nums.sum
      //每个f返回结果的形式   hello -> 4
      (f._1,counts)
    })
    println(result)

  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值