您的位置:首页 > 理论基础 > 数据结构算法

Scala中最常用数据结构Map和Tuple

2017-01-10 16:24 405 查看
package com.supeng.spark.scala

/**

 * 1,默认情况下Map构造的是不可变的集合,里面的内容不可以修改,一旦修改就变成新的Map,原有的Map内容保持不变

 * 2,Map的实例是调用工厂方法模式apply来构造Map实例,而需要主要的是Map接口,在apply中使用了具体的实现。

 * 3,如果想直接new出Map实例,需要使用HashMap等具体的Map子类

 * 4,查询一个Map中的值一定是采用getOrElse的语法的,一方面是key不存在时不报异常,另外可以提供默认值

 *    而关于默认值的提供在实际开发中至关重要,在spark开发中很多默认值都是通过getorElse的方式实现的。

 * 5,使用SortedMap 可以得到排序的Map集合

 * 6,LinkedHashMap可以记住插入的数据顺序,这在实际开发中非常有用

 * 7,Tuple中有很多不同类型的数据,例如  ("tom","lilei",30,"I am into Spark so much!!!");

 * 8,在企业级实际开发大数据的时候,一定会反复的使用Tuple来表达数据结构,以及使用Tuple来处理业务逻辑

 * 9,Tuple的另外一个非常重要的作用是作为函数的返回值,在Tuple中返回若干个值,以SparkContext源码为例来说明

 *    val (sched, ts) = SparkContext.createTaskScheduler(this, master)

 *  _schedulerBackend = sched

 *  _taskScheduler = ts

 */

object HelloMapTuple {

  def main(args :Array[String]) :Unit ={

    val bigDatas = Map("Spark"-> 6,"Hadoop"-> 7)  //调用工厂方法模式apply来构造Map实例,而需要主要是Map是接口,在apply中使用具体的实现类

   

    val persons = Map(("jialin",30),("spark",1))

   

    val programingLanguage = scala.collection.mutable.Map("scala"->13,"Java"->10)

    programingLanguage("scala")=15

    for((name,age) <-programingLanguage) println(name + " : "+ age)

   

    println(programingLanguage.getOrElse("defalut", 111))

    println("--------------------------")

       

    val personsInformation = new scala.collection.mutable.HashMap[String,Int]

    personsInformation += ("Scala"-> 13,"Java"-> 23)

    for((name,age)<-personsInformation) println(name +" : " + age)

    println("--------------------------")

   

    personsInformation -= ("Java")

    for((name,age)<-personsInformation) println(name +" : " + age)

    println("--------------------------")

   

    for(key <- personsInformation.keySet) println(key)

   

     println("--------------------------")

    

    

     for(value<- personsInformation.values) println(value)

    

     var result = for((name,age) <- personsInformation) yield (age,name)

    

     println("--------------------------")

      for((age,name)<-personsInformation) println(age +" : " + name)

    

     

         val persons2 = scala.collection.immutable.SortedMap(("jialin",30),("dtspark",1),("scala",12))

        

         for((name,age)<-persons2) println(name +" : " + age)

        

         val information = ("tom","lilei",30,"I am into Spark so much!!!")

         println(information._4)

  }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: