您的位置:首页 > 其它

scala Map 和 Tuple操作

2016-12-02 18:56 204 查看
package com.sparktest

/**
* 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,可以记住插入的数据的顺序,这在实际开发中非常有用
*/
object HelloMapTuple {
def main(args: Array[String]): Unit = {

val bitDatas = Map("Spark" -> 6, "Hadoop" -> 11) //调用工厂方法模式apply来构造Map实例,而需要注意的是Map是接口

val propramingLanguage = scala.collection.mutable.Map("Scala" -> 13, "Java" -> 23)

propramingLanguage("Scala") = 15

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

val persons = Map(("Dog", 1), ("Cat", 2))
println(persons.getOrElse("Python3", "Dog"))

val personsInfo = new scala.collection.mutable.HashMap[String, Int] //子类
personsInfo += ("Spark" -> 6, "Hadoop" -> 11)
personsInfo -= ("Spark", "Hadoop")

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

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

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

val result = for ((name, age) <- personsInfo) yield (age, name)
for ((age, name) <- result) println(name + ": " + age)

val persons2 = scala.collection.immutable.SortedMap(("hello",1),("world",2))

val personsInfo2 = new scala.collection.mutable.LinkedHashMap[String, Int] //子类
personsInfo2 += ("Spark" -> 6, "Hadoop" -> 11)
}
}


package com.sparktest

/**
* 1.Tuple中可以有很多不同类型的数据
* 2.在企业级中实际开发大数据的时候,一定会反复使用Tuple来表达数据结构,以及使用Tuple来处理业务逻辑
* 3.Tuple另外一个非常重要的作用是作为函数的返回值,在Tuple中返回若干个值,以SparkContext为例
* //create and start the scheduler
* val (sched,ts) = SparkContext.createTaskScheduler(this,master)
* _schedulerBackend = sched
* _taskScheduler = ts
*/
object HelloMapTuple {
def main(args: Array[String]): Unit = {

val info = ("Dog", "male", "1","like to eat meat")
println(info._3)//1
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: