Latest web development tutorials

Scala List (list)

Scala List (list)

Scala collections Scala collections

Scala list is similar to an array, they are the same type of all the elements, but they are different: The list is immutable, the value can not be changed once they are defined, followed by a list with recursive structure (that is, the link table structure) and an array No. .

Element type T can be written as a list of List [T]. For example, the following shows a list of various types:

// 字符串列表
val site: List[String] = List("w3big", "Google", "Baidu")

// 整型列表
val nums: List[Int] = List(1, 2, 3, 4)

// 空列表
val empty: List[Nothing] = List()

// 二维列表
val dim: List[List[Int]] =
   List(
      List(1, 0, 0),
      List(0, 1, 0),
      List(0, 0, 1)
   )

Two basic unit structure of the list isNil and ::

Nil can also be expressed as an empty list.

We can write the above examples are as follows:

// 字符串列表
val site = "w3big" :: ("Google" :: ("Baidu" :: Nil))

// 整型列表
val nums = 1 :: (2 :: (3 :: (4 :: Nil)))

// 空列表
val empty = Nil

// 二维列表
val dim = (1 :: (0 :: (0 :: Nil))) ::
          (0 :: (1 :: (0 :: Nil))) ::
          (0 :: (0 :: (1 :: Nil))) :: Nil

List of Basic Operating

Scala list has three basic operations:

  • head returns the first element of the list
  • tail returns a list that contains in addition to the other elements of the first element
  • isEmpty returns true if the list is empty

For Scala list any operation can be used to express the three basic operations. Examples are as follows:

object Test {
   def main(args: Array[String]) {
      val site = "w3big" :: ("Google" :: ("Baidu" :: Nil))
      val nums = Nil

      println( "第一网站是 : " + site.head )
      println( "最后一个网站是 : " + site.tail )
      println( "查看列表 site 是否为空 : " + site.isEmpty )
      println( "查看 nums 是否为空 : " + nums.isEmpty )
   }
}

Implementation of the above code, the output is:

$ vim Test.scala 
$ scala Test.scala 
第一网站是 : w3big
最后一个网站是 : List(Google, Baidu)
查看列表 site 是否为空 : false
查看 nums 是否为空 : true

Connection List

You can use the::: operator or List. :: :()Method orList.concat ()method to connect two or more lists. Examples are as follows:

object Test {
   def main(args: Array[String]) {
      val site1 = "w3big" :: ("Google" :: ("Baidu" :: Nil))
      val site2 = "Facebook" :: ("Taobao" :: Nil)

      // 使用 ::: 运算符
      var fruit = site1 ::: site2
      println( "site1 ::: site2 : " + fruit )
      
      // 使用 Set.:::() 方法
      fruit = site1.:::(site2)
      println( "site1.:::(site2) : " + fruit )

      // 使用 concat 方法
      fruit = List.concat(site1, site2)
      println( "List.concat(site1, site2) : " + fruit  )
      

   }
}

Implementation of the above code, the output is:

$ vim Test.scala 
$ scala Test.scala 
site1 ::: site2 : List(w3big, Google, Baidu, Facebook, Taobao)
site1.:::(site2) : List(Facebook, Taobao, w3big, Google, Baidu)
List.concat(site1, site2) : List(w3big, Google, Baidu, Facebook, Taobao)

List.fill ()

We can use List.fill () method to create a specified number of repetitions of a list of elements:

object Test {
   def main(args: Array[String]) {
      val site = List.fill(3)("w3big") // 重复 w3big 3次
      println( "site : " + site  )

      val num = List.fill(10)(2)         // 重复元素 2, 10 次
      println( "num : " + num  )
   }
}

Implementation of the above code, the output is:

$ vim Test.scala 
$ scala Test.scala 
site : List(w3big, w3big, w3big)
num : List(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)

List.tabulate ()

List.tabulate () method is used to create the list by the given function.

The first argument is the number of elements, which can be two-dimensional, the second parameter for the specified function, we calculate the results by specifying the function and returns the value inserted into the list, the start value is 0, the examples are as follows:

object Test {
   def main(args: Array[String]) {
      // 通过给定的函数创建 5 个元素
      val squares = List.tabulate(6)(n => n * n)
      println( "一维 : " + squares  )

      // 创建二维列表
      val mul = List.tabulate( 4,5 )( _ * _ )      
      println( "多维 : " + mul  )
   }
}

Implementation of the above code, the output is:

$ vim Test.scala 
$ scala Test.scala 
一维 : List(0, 1, 4, 9, 16, 25)
多维 : List(List(0, 0, 0, 0, 0), List(0, 1, 2, 3, 4), List(0, 2, 4, 6, 8), List(0, 3, 6, 9, 12))

List.reverse

List.reverse sequence for inverted list, examples are as follows:

object Test {
   def main(args: Array[String]) {
      val site = "w3big" :: ("Google" :: ("Baidu" :: Nil))
      println( "site 反转前 : " + site )

      println( "site 反转前 : " + site.reverse )
   }
}

Implementation of the above code, the output is:

$ vim Test.scala 
$ scala Test.scala 
site 反转前 : List(w3big, Google, Baidu)
site 反转前 : List(Baidu, Google, w3big)

Scala List common methods

The following table lists the Scala List common methods:

No. Method and Description
1

def + :( elem: A): List [A]

Add to the list of pre-elements

scala> val x = List(1)
x: List[Int] = List(1)

scala> val y = 2 +: x
y: List[Int] = List(2, 1)

scala> println(x)
List(1)
2

def: :( x: A): List [A]

In the beginning of the list to add elements

3

def :: :( prefix: List [A ]): List [A]

In the beginning of the list to add the specified list element

4

def: + (elem: A) : List [A]

After you copy the list to add elements.

scala> val a = List(1)
a: List[Int] = List(1)

scala> val b = a :+ 2
b: List[Int] = List(1, 2)

scala> println(a)
List(1)
5

def addString (b: StringBuilder): StringBuilder

Add all the elements of the list to StringBuilder

6

def addString (b: StringBuilder, sep : String): StringBuilder

Add all the elements of the list to StringBuilder, and specify the delimiter

7

def apply (n: Int): A

Get a list of elements by index

8

def contains (elem: Any): Boolean

Detecting whether the list contains the specified element

9

def copyToArray (xs: Array [A ], start: Int, len: Int): Unit

Copies the elements of the list into an array.

10

def distinct: List [A]

Remove duplicate elements of the list, and returns a new list

11

def drop (n: Int): List [A]

Discard the first n elements, and returns a new list

12

def dropRight (n: Int): List [A]

Discard the last n elements, and returns a new list

13

def dropWhile (p: (A) => Boolean): List [A]

Discard element left to right, until the condition is not satisfied p

14

def endsWith [B] (that: Seq [B]): Boolean

Detecting whether the list at the end of the specified sequence

15

def equals (that: Any): Boolean

Determine whether the same

16

def exists (p: (A) => Boolean): Boolean

Analyzing the conditions specified in the list of elements exists.

L determine whether there is an element:

scala> l.exists(s => s == "Hah")
res7: Boolean = true
17

def filter (p: (A) => Boolean): List [A]

All elements of output symbols specified condition.

The length of the filter element 3:

scala> l.filter(s => s.length == 3)
res8: List[String] = List(Hah, WOW)
18

def forall (p: (A) => Boolean): Boolean

Detection of all elements.

For example: to determine whether all the elements of "H" at the beginning:

scala> l.forall (s => s.startsWith ( "H")) res10: Boolean = false
19

def foreach (f: (A) => Unit): Unit

All elements of the function to the list

20

def head: A

Get the first element of the list

twenty one

def indexOf (elem: A, from : Int): Int

Find the location of the first occurrence of the element from the specified location from

twenty two

def init: List [A]

Returns all elements, except the last one

twenty three

def intersect (that: Seq [A ]): List [A]

Calculating a plurality of the intersection of sets

twenty four

def isEmpty: Boolean

Detecting whether the list is empty

25

def iterator: Iterator [A]

Create a new iterator to iterate the elements

26

def last: A

Returns the last element

27

def lastIndexOf (elem: A, end : Int): Int

At the location specified end position start looking for the last occurrence of the element

28

def length: Int

Back to the list length

29

def map [B] (f: (A) => B): List [B]

Through a given method will recalculate all the elements

30

def max: A

Find the maximum element

31

def min: A

Find the smallest element

32

def mkString: String

Display a list of all the elements as a string

33

def mkString (sep: String): String

Separators will display a list of all the elements as a string

34

def reverse: List [A]

Reverse list

35

def sorted [B>: A] : List [A]

List Sorting

36

def startsWith [B] (that: Seq [B], offset: Int): Boolean

Detecting whether the list contains the specified sequence at the specified location

37

def sum: A

Calculation and collection of elements

38

def tail: List [A]

Returns all elements, except the first one

39

def take (n: Int): List [A]

Extracting the first n elements of the list

40

def takeRight (n: Int): List [A]

n elements extracted list

41

def toArray: Array [A]

List to an array

42

def toBuffer [B>: A] : Buffer [B]

Back buffer contains a list of all the elements

43

def toMap [T, U]: Map [T, U]

List converted Map

44

def toSeq: Seq [A]

List convert Seq

45

def toSet [B>: A] : Set [B]

List convert Set

46

def toString (): String

Converted to a string list

More ways to refer to the API documentation

Scala collections Scala collections