zoukankan      html  css  js  c++  java
  • 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
      }
    }
  • 相关阅读:
    js变量如何赋值给css使用?
    前端预览与下载PDF小结
    子组件如何改父组件传过来的值
    TensorRT转换时的静态模式与动态模式
    Linux:搭建GlusterFS文件系统
    OpenFeign传输文件MultipartFile
    Docker:commit、export、import、save、load命令的使用
    Git:代码版本回退
    docker安装Drools Workbench
    ArchLinux:Typora设置gitee图床
  • 原文地址:https://www.cnblogs.com/yin-fei/p/10827071.html
Copyright © 2011-2022 走看看