生活随笔
收集整理的這篇文章主要介紹了
Scala _05集合_数组(一)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
集合
數組
new Array[Int](10)
賦值:arr(0) = xxx
? ? ?2.Array[String](“s1”,”s2”,”s3”)
forforeach
Array.concate:合并數組Array.fill(5)(“bjsxt”):創建初始值的定長數組
package com.henu.scala04CollectionAndArrayobject ArrayDemo {def main(args: Array[String]): Unit = {/*** 創建數組兩種方式:* 1.new Array[String](3)* 2.直接Array*///創建類型為Int 長度為3的數組val arr1 = new Array[Int](3)//創建String類型的數組,直接賦值val arr2 = Array[String]("george","love","kangkang")//賦值arr1(0) = 100arr1(1) = 200arr1(2) = 300/*** 遍歷的兩種方式*/for (i <- arr1){println(i)}arr1.foreach(i =>{println(i)})for (s <- arr2){println(s)}arr2.foreach(s =>{println(s)})}
}
package com.henu.scala04CollectionAndArrayobject TwoArray {def main(args: Array[String]): Unit = {//創建二維數組val arr = new Array[Array[String]](3)arr(0) = Array("George","love","Sweetie")arr(1) = Array("George","love","Honey")arr(2) = Array("George","love","kangkang")//循環遍歷二維數組for (i <- 0 until arr.length){for (j <- 0 until arr(i).length){print(arr(i)(j) + " ")}println()}var count = 0//創建數組val arr2 = Array[String]("honey","love","george")//輸出二維數組for (a <- arr2; i <- arr2){if (count %3 == 0){println()}print(i + " ")count +=1}println()/*arr2.foreach{ a=>println(a)}for (a <- arr){println(a)}*/arr2.foreach{ a => {a.foreach{println}}}//創建二維數組val arr3 = Array[Array[Int]](Array(1,2,3),Array(4,5,6))//遍歷二維數組arr3.foreach({ a => {a.foreach(i=>{println(i)})}})for (a <- arr3; i <- a){println(i)}}
}
自行查閱API
//可變長數組的定義val array = ArrayBuffer[String]("g","e","o")array.append("hello","scala")//在后面追加多個元素array.+=("end")//在最后追加元素array.+=:("Start")//在開頭追加元素arr.foreach(println)for (i <- array){print(i + " ")}
list
val list = List(1,2,3,4)Nil長度為0的list
foreach ,for
filter:過濾元素count:計算符合條件的元素個數map:對元素操作flatmap :壓扁扁平,先map再flat
?
package com.henu.Scala05Listobject ListDemo01 {def main(args: Array[String]): Unit = {//創建val list = List(1,2,3,4,5)//遍歷list.foreach{a => println(a)}list.foreach(println)//filterval list1 = list.filter{x => x>3}list1.foreach(println)//countval value = list1.count(x => x>3)println(value)//mapval nameList = List("hello george","hello george","hello george")println("###############################")val mapResult:List[Array[String]] = nameList.map(x => x.split("h"))mapResult.foreach( a =>a.foreach(println))println("###############################")//flatmapval flatMapResult : List[String] = nameList.flatMap( x => x.split(" "))//為了更好理解,將其循環這樣輸出flatMapResult.foreach( a=>a.foreach( i =>{print(i +" ")}))}
}
?
詳情見API? ??https://www.scala-lang.org/api/2.11.12/#scala.collection.immutable.List
//可變長的listval listBuffer : ListBuffer[Int] = ListBuffer[Int](1,2,3,4,5)listBuffer.append(6,7,8,9)listBuffer.+=(10)//最最后追加元素listBuffer.+=:(100)//在開頭加入元素listBuffer.foreach(println)
?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生
總結
以上是生活随笔為你收集整理的Scala _05集合_数组(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。