map+case结构使用技巧

people.txt文本如下

复制代码
lyzx1,19
lyzx2,20
lyzx3,21
lyzx4,22
lyzx5,23
lyzx6,24
lyzx7,25
lyzx7,25,哈哈
托塔天王
复制代码
复制代码
  def main(args: Array[String]): Unit = {

    //    val conf = new SparkConf().setAppName("ProductSalesStat").setMaster("local[*]")
    //    val sc = new SparkContext(conf)
    //    val words = Array("one", "two", "two", "three", "three", "three")
    //    val wordPairsRDD: RDD[(String, Int)] = sc.parallelize(words).map(word => (word, 1))
    //        val wordCountsWithReduce = wordPairsRDD
    //          .reduceByKey(_ + _)
    //          .collect()
    //    wordCountsWithReduce.foreach(println)
    //    sc.stop()
    //  }

    val conf = new SparkConf().setAppName("ProductSalesStat").setMaster("local[*]")
    val sparkContext = new SparkContext(conf)
    val rdd = sparkContext.textFile("E:\\Data\\LIVE-DATA-SPARK\\src\\main\\resources\\people.txt")
    rdd.map(line => line.split(","))
      .map(
        rt => if (rt.length == 1) rt(0)
        else if (rt.length == 2) (rt(0), rt(1))
        else (rt(0), rt(1), rt(2))
      )
      .map {
        case (one: String) => "one:" + one
        case (name: String, age: String) => ("name:" + name, "age:" + age)
        case _ => ("_name", "_age", "_")
      }
      .foreach(println)
  }
}
复制代码

 

posted @   Bonnie_ξ  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示