6.Scala中的Map和Tupple


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

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

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

4.查询一个Map中的值,一定采用getOrElese的语法,一方面在key不存在的情况下不报异常,还有一个作用就是提供默认的值;

5.使用SortMap可以得到排序的Map的集合

6.LinkedHashMap可以得到排序的Map集合

7.Tuple中可以有很多不同类型的数据,例如(“I am geeksu”,"male",18,"I like Spark")

8.Tuple另外一个非常重要的作用是作为函数的返回值,返回值的Tuple中返回若干值。Spark源码例子:

 val (sched, ts) = SparkContext.createTaskScheduler(this, master, deployMode)
    _schedulerBackend = sched
    _taskScheduler = ts

9.scala实例

object HelloMapTuple {
  def main(args: Array[String]): Unit = {
    //调用工厂方法模式apply来构造Map实例,而需要注意的是Map是接口,在apply中使用了具体的实现
    val bigData = Map("Spark" -> 6,"Hadoop" -> 11)
    //第二种写法
    //  val persons = Map(("It",21),("Project",10))
    val persons = scala.collection.immutable.SortedMap("Scala" -> 13,"Java" -> 23)

    val language = scala.collection.mutable.Map("Scala"->13,"Java" -> 23)
    language("scala") = 15
    for((name,age) <- language) println(name + ":" + age)

    println(language.getOrElse("Python","does not exit this key"))
    val personsInformation = new mutable.HashMap[String,Int]()
    personsInformation += ("scala" -> 12,"Java" -> 25)
    personsInformation -= ("Java")
    for((name,age) <- personsInformation) println(name + " : " + age)
    //只遍历key
    for(key <- personsInformation.keySet) println(key)
    //只遍历value
    for(value <- personsInformation.values) println(value)

    //利用已有的Map构建新的Map(key,value交换)
    val result = for((name,age) <- personsInformation) yield (age,name)
    for((name,age) <- result) println(name + ":" + age) //12:scala

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

    //LinkedHashMap的使用 --> 使用插入顺序
    val personInfoLiked = new scala.collection.mutable.LinkedHashMap[String,Int]
    personInfoLiked += ("hive" -> 12,"Hbase" -> 9,"Kafka" -> 100)

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

    val information = ("woshiwangjialin","male",30,"I am into spark too much")
    println(information._1)
    println(information._2)
    println(information._3)
  }

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值