【scala】 scala 映射和元组操作(四)
1、映射 Map
定义 ,取值,遍历,排序
2. 元组
定义,取值,拉链操作
import scala.collection.mutable /** * 映射和元组 * * @author xwolf * @date 2017-04-12 11:23 * @since 1.8 */ object MapTest { def main(args: Array[String]): Unit = { tuple() } private def map(): Unit ={ //定义映射 ->对偶操作 var map =Map("id"->1,"name"->"王思琪",("age",10)) var twoMap = Map("detail"->"优秀屌丝","state"->0) // += 添加K-V map += ("birth"->"20160101") //移除 key value map -= "id" //两个映射合并 val newMap = map ++ twoMap println(newMap) println(map("name"))//map取值 val name = if (map.contains("name1")) map("name") else None println(name) //映射遍历 for (elem <- map) { println(elem) } for((k,v)<-map){ println(k+","+v) } val keys = map.keySet for(k<-keys){ println("k="+k+",value="+map(k)) } // k v 互换 生成新的map val kMap = for((k,v)<-map) yield (v,k) println(kMap) //有序map 底层是java 的TreeMap val sortMap= mutable.SortedMap("a"->1,"age"->122,"state"->0,"name"->"老王") println(sortMap) } /** * 元组操作 */ def tuple(): Unit ={ //元组定义 val tuple =(1,2,12,4,15) println(tuple) println(tuple._3)//获取第三个元素,非下标 println(tuple _3)//获取第三个元素,非下标 val one = Array("Hello","Scala","Java") val two =Array(1,2,3) //拉链操作 将两个数组合并为Map val ou =one.zip(two) println(ou.toBuffer) } }