Scala映射与元组

注释很详细,看代码吧


object MapDemo {
  def main(args: Array[String]): Unit = {
    val A = Map(1->10,2->20)
    val B = Map((1,10),(2,20))
    println(A(1))
    println(B.get(1))
    println(A.contains(1))
    println(A.getOrElse(3,"don't have the key"))
    //遍历
    for((i,j)<-A)println("A:"+i+"---"+j)
    //互换键值
    val C = for((i,j)<-B) yield(j,i)
    for((i,j)<-C)println("C:"+i+"---"+j)
    //获得映射键的集合
    val keySet = A.keySet
    println(keySet)
    //获得映射值的集合
    val valSet = A.values
    println(valSet)
    //元组
    val tuple = (1,1.2,'a')
    println(tuple._1)
    println(tuple _2)
    //zip结合集合
    val a = Array('a','b','c')
    val b = Array(1,2,3)
    //生成二元数组Array((a,1),(b,2),(c,3))
    val c = a.zip(b)
    val d = a zip b
    //生成映射Map(a -> 1, b -> 2, c -> 3)
    val e = a zip b toMap
  }
}


你可能感兴趣的:(Scala)