其他分享
首页 > 其他分享> > 15_Scala_test02_wordcount02

15_Scala_test02_wordcount02

作者:互联网

package chapter07

import myutils.Print_everything

/**
 * @Auther: HYBG
 * @Date: 2021/7/6 14:09
 * @Description: Scala13_wordcount
 * @Version 1.0.0
 */
object Scala13_wordcount {

  def main(args: Array[String]): Unit = {
    // ("Hello Scala", 4) 表示 "Hello Scala" 出现4次
    val tuples = List(("Hello Scala", 4), ("Hello Spark", 2), ("Hello beijing", 3), ("Hello shanghai", 5))

    Print_everything.print_equals("分开写")
    //将数据转化为分开的多个
    val strings: List[String] = tuples.map(map => ((map._1 + " ") * map._2))
    println(strings)
    //List(Hello Scala Hello Scala Hello Scala Hello Scala , Hello Spark Hello Spark , Hello beijing Hello beijing Hello beijing , Hello shanghai Hello shanghai Hello shanghai Hello shanghai Hello shanghai )
    //将数据进行分开
    val strings1: List[String] = strings.flatMap(_.split(" "))
    println(strings1)
    //将数据进行分组
    val stringToStrings: Map[String, List[String]] = strings1.groupBy(word => word)
    println(stringToStrings)
    //对个每个单词进行计数
    val stringToInt: Map[String, Int] = stringToStrings.map(count => (count._1, count._2.length))
    println(stringToInt)
    //将map转换为list集合
    val list: List[(String, Int)] = stringToInt.toList
    println(list)
    //对list集合进行排序
    val tuples1: List[(String, Int)] = list.sortBy(tuple => tuple._2)
    println(tuples1)

    //简写
    Print_everything.print_equals("简写")
    println((tuples.map(words => (words._1 + " ") * words._2)).flatMap(word => word.split(" ")).groupBy(word => word).map(count => (count._1, count._2.length)).toList)

    Print_everything.print_equals("思路2")
    //将("Hello Scala", 4) 转换为("Hello", 4) ("Scala", 4)
    println(tuples.map(word => word._1.split(" ").map(word1 => (word1, word._2))).flatten.groupBy(word2 => word2._1).map(word3 => (word3._1, word3._2.map(_._2).sum)).toList)
    
  }

}

标签:map,15,String,Scala,word,._,test02,wordcount02,Hello
来源: https://www.cnblogs.com/HYBG-JXMD/p/14978723.html