scala映射与元祖

博客介绍了Scala中的相关操作,包括构造映射、获取和更新映射中的值、迭代映射,还提及了元祖和拉链操作。这些内容有助于掌握Scala在数据处理方面的应用。

1.构造映射

object Test {

  def main(args: Array[String]): Unit = {
    //不可变映射
    val scores1 = Map("alice" -> 90, "tom" -> 100) // 值不能被改变
    val scores2 = Map(("alice", 90), ("tom", 100))
    //可变映射
    val scores3 = scala.collection.mutable.Map("alice" -> 90, "tom" -> 100)

    //空的映射
    val map = scala.collection.mutable.HashMap[String, Int]

  }
}

 

2.获取映射中的值

 

object Test {

  def main(args: Array[String]): Unit = {

    val scores1 = Map("alice" -> 90, "tom" -> 100)
    // 获取值
    println(scores1("alice")) //没有的话报错

    println(scores1.getOrElse("lili", 80))

    println(scores1.get("alice")) //Some(90)  没有 None  Option对象

  }
}

 

3.更新映射中的值

 

object Test {

  def main(args: Array[String]): Unit = {

    val scores1 = scala.collection.mutable.Map("alice" -> 90, "tom" -> 100)
    scores1("alice") = 100
    println(scores1("alice")) //100
    scores1("zhangsan") = 80 //没有该键,则添加
    println(scores1("zhangsan"))

    //添加多个
    scores1 += ("lili" -> 70, "sam" -> 60)

    //移除
    scores1 -= "sam"
  }
}

 

4.迭代映射

 

object Test {

  def main(args: Array[String]): Unit = {

    val scores1 = scala.collection.mutable.Map("alice" -> 90, "tom" -> 100)
    //迭代
    //获取所有键
    for (i <- scores1.keySet) {
      print(i + "--")
    }
    println()
    for (i <- scores1.keys) {
      print(i + "--")
    }
    println()
    //获取所有值
    for (i <- scores1.values) {
      print(i + "--")
    }
    println()
    //获取键值对
    for ((k, v) <- scores1) {
      println((k, v) + "--")
    }
  }
}

 

5.元祖

 

object Test {

  def main(args: Array[String]): Unit = {

    val tuple = (1,2,"a","b")
    println(tuple._1)
  }
}

 

7.拉链操作

 

object Test {

  def main(args: Array[String]): Unit = {

    val tuple = (1, 2, "a", "b")
    println(tuple._1)
    val a = Array(1, 2, 3)
    val b = Array("a", "b", "c")
    val c = a.zip(b)
    for ((k, v) <- c) {
      println((k, v))
    }
    //    (1,a)
    //    (2,b)
    //    (3,c)
    c.toMap
  }
}

 

转载于:https://www.cnblogs.com/yin-fei/p/10827071.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值