美文网首页
scala集合

scala集合

作者: 松松土_0b13 | 来源:发表于2019-10-13 19:33 被阅读0次

    定长数组

    val a = new Array[String](5)  //类似java的String[]
    a.length
    a(1)="11"
    
    val b = Array(1,2,3,4,5,6)
    b.sum
    b.mkString()
    b.mkString(",")
    b.mkString("<",",",">") // ==> <1,2,3,4,5,6>
    

    可变数组

    scala.collection.mutable.ArrayBuffer

    val c = scala.collection.mutable.ArrayBuffer[Int]()
    c += 1
    c += (2,3)
    c ++= Array(4,5)
    c.insert(0,0)
    c.toArray
    

    List

    val l = List(1,2,3,4,5)
    l.head
    l.tail
    val l2 = 1 :: Nil
    l2.isEmpty
    l2.tail:_* // => 可以转化成可变参数: Int*
    

    Set

    无序,不可重复

    • scala的set对象实例可以转化为java.util.set
    val ints = scala.collection.mutable.Set[Int]()
    //引入scala.collection.JavaConverters用于Scala与Java集合的互转
    import scala.collection.JavaConverters._
    ints.asJava // => java.util.set
    

    Map

    val a = Map("aa" -> 1)
    val b = scala.collection.mutable.Map("aa" -> 2)
    val c = scala.collection.mutable.HashMap[String,Int]()
    b("aa")  // 有可能会报错
    b.get("aa") // => Some  (Option[Int])
    b.getOrElse("aa", 2)
    b += ("bb" -> 3)
    
    for((key,value) <- b) {
        println(key)
    }
    for(key <- b.keySet) {
        println(key)
    }
    for(value <- b.values) {
        println(value)
    }
    

    Option | Some | None

    val m = Map(1 -> 2)
    m.get(2).isEmpty
    println(m.get(1).get)
    

    元组tuple

    val a = (1,23,4,5,6)
    a._1
    
    for(i <- 0 until(a.productArity))
    
    val (aa, bb, cc, dd) = Array(1,2,3,4)
    

    相关文章

      网友评论

          本文标题:scala集合

          本文链接:https://www.haomeiwen.com/subject/uikfmctx.html