把Scala List的幾種常見方法梳理彙總以下,平常開發場景基本上夠用了。es6
建立列表es5
scala> val days = List("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
scala
days: List[String] = List(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)
code
建立空列表排序
scala> val l = Nil
索引
l: scala.collection.immutable.Nil.type = List()
開發
scala> val l = List()
字符串
l: List[Nothing] = List()
it
用字符串建立列表io
scala> val l = "Hello" :: "Hi" :: "Hah" :: "WOW" :: "WOOW" :: Nil
l: List[String] = List(Hello, Hi, Hah, WOW, WOOW)
用「:::」疊加建立新列表
scala> val wow = l ::: List("WOOOW", "WOOOOW")
wow: List[String] = List(Hello, Hi, Hah, WOW, WOOW, WOOOW, WOOOOW)
經過索引獲取列表值
scala> l(3)
res0: String = WOW
獲取值長度爲3的元素數目
scala> l.count(s => s.length == 3)
res1: Int = 2
返回去掉l頭兩個元素的新列表
scala> l.drop(2)
res2: List[String] = List(Hah, WOW, WOOW)
scala> l
res3: List[String] = List(Hello, Hi, Hah, WOW, WOOW)
返回去掉l後兩個元素的新列表
scala> l.dropRight(2)
res5: List[String] = List(Hello, Hi, Hah)
scala> l
res6: List[String] = List(Hello, Hi, Hah, WOW, WOOW)
判斷l是否存在某個元素
scala> l.exists(s => s == "Hah")
res7: Boolean = true
濾出長度爲3的元素
scala> l.filter(s => s.length == 3)
res8: List[String] = List(Hah, WOW)
判斷全部元素是否以「H」打頭
scala> l.forall(s => s.startsWith("H"))
res10: Boolean = false
判斷全部元素是否以「H」結尾
scala> l.forall(s => s.endsWith("W"))
res11: Boolean = false
打印每一個元素
scala> l.foreach(s => print(s + ' '))
Hello Hi Hah WOW WOOW
取出第一個元素
scala> l.head
res17: String = Hello
取出最後一個元素
scala> l.last
res20: String = WOOW
剔除最後一個元素,生成新列表
scala> l.init
res18: List[String] = List(Hello, Hi, Hah, WOW)
剔除第一個元素,生成新列表
scala> l.tail
res49: List[String] = List(Hi, Hah, WOW, WOOW)
判斷列表是否爲空
scala> l.isEmpty
res19: Boolean = false
得到列表長度
scala> l.length
res21: Int = 5
修改每一個元素,再反轉每一個元素造成新列表
scala> l.map(s => {val s1 = s + " - 01"; s1.reverse})
res29: List[String] = List(10 - olleH, 10 - iH, 10 - haH, 10 - WOW, 10 - WOOW)
生成用逗號隔開的字符串
scala> l.mkString(", ")
res30: String = Hello, Hi, Hah, WOW, WOOW
反序生成新列表
scala> l.reverse
res41: List[String] = List(WOOW, WOW, Hah, Hi, Hello)
按字母遞增排序
scala> l.sortWith(_.compareTo(_) < 0)
res48: List[String] = List(Hah, Hello, Hi, WOOW, WOW)