Scala List的一些常用方法

Scala List的常用方法,梳理出來
創建空列表

scala> val arr1 = Nil
arr1: scala.collection.immutable.Nil.type = List()

scala> val arr1 = List()
arr1: List[Nothing] = List()

創建帶有值得列表

scala> val arr1 = List("list","hashmap","scala","temp")
arr1: List[String] = List(list, hashmap, scala, temp)

scala> val arr1 = "list"::"hashmap"::"scala"::"temp"::Nil
arr1: List[String] = List(list, hashmap, scala, temp)

通過索引獲取列表值

scala> arr1(2)
res2: String = scala

移除元素

#返回移除前兩個元素的arr1列表
scala> arr1.drop(2)
res3: List[String] = List(scala, temp)

#返回移除後兩個元素的arr1列表
scala> arr1.dropRight(2)
res4: List[String] = List(list, hashmap)

計算長度爲4的String元素個數

scala> arr1.count(s=>s.length ==4)
res5: Int = 2

判斷元素是否存在

scala> arr1.exists(s=> s == "temp")
res6: Boolean = true

返回長度爲4的元素組成的新列表

scala> arr1.filter(s => s.length ==4)
res7: List[String] = List(list, temp)

判斷列表的元素是否都以"1"結尾

scala> arr1.forall(s => s.endsWith("1"))
res8: Boolean = false

對列表每個元素執行println語句

scala> arr1.foreach(s => println(s))
list
hashmap
scala
temp

scala> arr1.foreach(println)
list
hashmap
scala
temp

返回列表的第一個元素

scala> arr1.head
res11: String = list

返回列表除最後一個元素外其他元素組成的列表

scala> arr1.init
res12: List[String] = List(list, hashmap, scala)

判斷列表是否爲空

scala> arr1.isEmpty
res13: Boolean = false

返回列表的最後一個元素

scala> arr1.last
res14: String = temp

返回列表元素數量

scala> arr1.length
res15: Int = 4

返回由列表元素添加了指定字符的新列表

scala> arr1.map(s => s +"yy")
res16: List[String] = List(listyy, hashmapyy, scalayy, tempyy)

返回列表元素組成的字符串

scala> arr1.mkString(":")
res17: String = list:hashmap:scala:temp

返回由列表元素逆序組成的新列表

scala> arr1.reverse
res20: List[String] = List(temp, scala, hashmap, list)

返回列表中除去第一個元素外依次組成的新列表

scala> arr1.tail
res21: List[String] = List(hashmap, scala, temp)

按字母遞增排序

scala> arr1.sortWith(_.compareTo(_) <0)
res24: List[String] = List(hashmap, list, scala, temp)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章