[scala基础]--map基本操作

    xiaoxiao2024-12-29  10

    运行环境:jdk1.7、scala-2.10.4 package study //数据结构map object TestMap { def main(args: Array[String]): Unit = { var m1=scala.collection.mutable.Map[String,Int](("tom",12),("jim",21)) var m2=scala.collection.immutable.Map[String,Int](("tom2",22),("jim2",21)) //取值 println("m1--->"+m1("tom")) println("m2--->"+m2("tom2")) //添加元素 m1+=("jony"->2) m2+=("jony2"->62) println("m1="+m1) println("m2="+m2) //遍历元素 m1.foreach(x=> {println("m1==>"+x._1)}) m2.foreach(x=> {println("m2==>"+x._2)}) //根据key得到值得遍历 m1.keys.foreach { x => {println("m1 的key is 【"+x)} } //直接遍历值 m2.values.foreach { x =>{println("m2 的value is 【"+x)} } } } 结果: m1--->12 m2--->22 m1=Map(jim -> 21, tom -> 12, jony -> 2) m2=Map(tom2 -> 22, jim2 -> 21, jony2 -> 62) m1==>jim m1==>tom m1==>jony m2==>22 m2==>21 m2==>62 m1 的key is  【jim m1 的key is  【tom m1 的key is  【jony m2 的value is 【22 m2 的value is 【21 m2 的value is 【62
    转载请注明原文地址: https://ju.6miu.com/read-1295123.html
    最新回复(0)