Scala經常使用List列表操做方法

把Scala List的幾種常見方法梳理彙總以下,平常開發場景基本上夠用了。es6

建立列表es5

  1. scala> val days = List("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")scala

  2. days: List[String] = List(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)code

建立空列表排序

  1. scala> val l = Nil索引

  2. l: scala.collection.immutable.Nil.type = List()開發

  3.  
  4. scala> val l = List()字符串

  5. l: List[Nothing] = List()it

用字符串建立列表io

  1. scala> val l = "Hello" :: "Hi" :: "Hah" :: "WOW" :: "WOOW" :: Nil

  2. l: List[String] = List(Hello, Hi, Hah, WOW, WOOW)

用「:::」疊加建立新列表

  1. scala> val wow = l ::: List("WOOOW", "WOOOOW")

  2. wow: List[String] = List(Hello, Hi, Hah, WOW, WOOW, WOOOW, WOOOOW)

經過索引獲取列表值

  1. scala> l(3)

  2. res0: String = WOW

獲取值長度爲3的元素數目

  1. scala> l.count(s => s.length == 3)

  2. res1: Int = 2

返回去掉l頭兩個元素的新列表

  1. scala> l.drop(2)

  2. res2: List[String] = List(Hah, WOW, WOOW)

  3.  
  4. scala> l

  5. res3: List[String] = List(Hello, Hi, Hah, WOW, WOOW)

返回去掉l後兩個元素的新列表

  1. scala> l.dropRight(2)

  2. res5: List[String] = List(Hello, Hi, Hah)

  3.  
  4. scala> l

  5. res6: List[String] = List(Hello, Hi, Hah, WOW, WOOW)

判斷l是否存在某個元素

  1. scala> l.exists(s => s == "Hah")

  2. res7: Boolean = true

濾出長度爲3的元素

  1. scala> l.filter(s => s.length == 3)

  2. res8: List[String] = List(Hah, WOW)

判斷全部元素是否以「H」打頭

  1. scala> l.forall(s => s.startsWith("H"))

  2. res10: Boolean = false

判斷全部元素是否以「H」結尾

  1. scala> l.forall(s => s.endsWith("W"))

  2. res11: Boolean = false

打印每一個元素

  1. scala> l.foreach(s => print(s + ' '))

  2. Hello Hi Hah WOW WOOW

取出第一個元素

  1. scala> l.head

  2. res17: String = Hello

取出最後一個元素

  1. scala> l.last

  2. res20: String = WOOW

剔除最後一個元素,生成新列表

  1. scala> l.init

  2. res18: List[String] = List(Hello, Hi, Hah, WOW)

剔除第一個元素,生成新列表

  1. scala> l.tail

  2. res49: List[String] = List(Hi, Hah, WOW, WOOW)

判斷列表是否爲空

  1. scala> l.isEmpty

  2. res19: Boolean = false

得到列表長度

  1. scala> l.length

  2. res21: Int = 5

修改每一個元素,再反轉每一個元素造成新列表

  1. scala> l.map(s => {val s1 = s + " - 01"; s1.reverse})

  2. res29: List[String] = List(10 - olleH, 10 - iH, 10 - haH, 10 - WOW, 10 - WOOW)

生成用逗號隔開的字符串

  1. scala> l.mkString(", ")

  2. res30: String = Hello, Hi, Hah, WOW, WOOW

反序生成新列表

  1. scala> l.reverse

  2. res41: List[String] = List(WOOW, WOW, Hah, Hi, Hello)

按字母遞增排序

  1. scala> l.sortWith(_.compareTo(_) < 0)

  2. res48: List[String] = List(Hah, Hello, Hi, WOOW, WOW)

相關文章
相關標籤/搜索