English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala List(List)

Scala Collections

Scala lists are similar to arrays, with all elements of the same type, but they also have some differences: lists are immutable, and once defined, their values cannot be changed; secondly, lists have a recursive structure (i.e., linked list structure) while arrays do not.

The element type T of the list can be written as List[T]. For example, the following lists various types of lists:

// string list
val site: List[String] = List("w3codebox", "Google", "Baidu")
// integer list
val nums: List[Int] = List(1, 2, 3, 4)
// empty list
val empty: List[Nothing] = List()
// two-dimensional list
val dim: List[List[Int]] =
   List(
      List(1, 0, 0),
      List(0, 1, 0),
      List(0, 0,) 1)
   )

the two basic units for constructing lists are Nil and ::

Nil It can also be represented as an empty list.

The above examples can be written as follows:

// string list
val site = "w3codebox" :: ("Google" :: ("Baidu" :: Nil)))
// integer list
val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
// empty list
val empty =
// two-dimensional list
val dim = (1 :: (0 :: (0 :: Nil))) ::
          (0 :: (1 :: (0 :: Nil))) ::
          (0 :: (0 :: (1 :: Nil))) :: Nil

List basic operations

Scala lists have three basic operations:

  • head returns the first element of the list

  • tail returns a list containing all elements except the first one

  • isEmpty returns true when the list is empty

Any operation on Scala lists can be expressed using these three basic operations. For example:

// string list
object Test {
   def main(args: Array[String]) {
      val site = "w3codebox" :: ("Google" :: ("Baidu" :: Nil)))
      val nums =
      println( "The first site is : " + site.head )
      println( "The last site is : " + site.tail )
      println( "Check if the list site is empty : " + site.isEmpty )
      println( "Check if nums is empty : " + nums.isEmpty )
   }
}

Execute the above code, the output result is:

$ vim Test.scala 
$ scala Test.scala 
The first site is : w3codebox
The last site is : List(Google, Baidu)
Check if the list site is empty : false
Check if nums is empty : true

to concatenate lists

You can use ::: operator or List.:::() method or List.concat() method to concatenate two or more lists. For example:

object Test {
   def main(args: Array[String]) {
      val site =1 "w3codebox" :: ("Google" :: ("Baidu" :: Nil)))
      val site =2 = "Facebook" :: ("Taobao" :: Nil)
      // using ::: operator
      var fruit = site1 ::: site2
      println( "site1 ::: site2 : " + fruit )
      
      // using List.:::() method
      fruit = site1.:::(site2)
      println( "site1.:::(site2) : " + fruit )
      // using concat method
      fruit = List.concat(site1, site2)
      println( "List.concat(site1, site2) : " + fruit )
      
   }
}

Execute the above code, the output result is:

$ vim Test.scala 
$ scala Test.scala 
site1 ::: site2 : List(w3codebox, Google, Baidu, Facebook, Taobao)
site1.:::(site2List(Facebook, Taobao, w3codebox, Google, Baidu)
List.concat(site)1, site2) : List(w3codebox, Google, Baidu, Facebook, Taobao)

List.fill()

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

object Test {
   def main(args: Array[String]) {
      val site = List.fill(3)("w3codebox) // repeated w3codebox 3times
      println("site : ", + site    )
      val num = List.fill(10)(2)         // repeated elements 2, 10 times
      println("num : ", + num    )
   }
}

Execute the above code, the output result is:

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

List.tabulate()

The List.tabulate() method creates a list through a given function.

The first parameter of the method is the number of elements, which can be two-dimensional, the second parameter is the specified function, we calculate the result through the specified function and return the value inserted into the list, starting with 0, for example:

object Test {
   def main(args: Array[String]) {
      // Create a list through a given function 5 elements
      val squares = List.tabulate(6)(n => n    ) * n    )
      println("One-dimensional : ", + squares    )
      // Create a two-dimensional list
      val mul = List.tabulate( 4,5 )( _, * _    )      
      println("Multi-dimensional : ", + mul    )
   }
}

Execute the above code, the output result is:

$ vim Test.scala 
$ scala Test.scala 
One-dimensional : List(0, 1, 4, 9, 16, 25)
Multi-dimensional : 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 is used to reverse the order of a list, for example:

object Test {
   def main(args: Array[String]) {
      val site = "w3codebox" :: ("Google" :: ("Baidu" :: Nil)))
      println("site before reversal : ", + site)
      println("site after reversal : ", + site.reverse)
   }
}

Execute the above code, the output result is:

$ vim Test.scala 
$ scala Test.scala 
site before reversal : List(w3codebox, Google, Baidu)
site reverse : List(Baidu, Google, w)3codebox)

Commonly Used Methods of Scala List

The following table lists the commonly used methods of Scala List:

Serial NumberMethod and Description
1

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

Prepend elements to the list

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]

Add an element at the beginning of the list

3

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

Add the elements of the specified list at the beginning of the list

4

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

Copy the list after adding 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 elements of the list to StringBuilder

6

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

Add all elements of the list to StringBuilder and specify a separator

7

def apply(n: Int): A

Get the element by list index

8

def contains(elem: Any): Boolean

Check if the list contains the specified element

9

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

Copy the elements of the list to an array.

10

def distinct: List[A]

Remove duplicate elements from the list and return a new list

11

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

Discard the first n elements and return a new list

12

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

Discard the last n elements and return a new list

13

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

Discard elements from left to right until the condition p does not hold

14

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

Check if the list ends with the specified sequence

15

def equals(that: Any): Boolean

Determine if they are equal

16

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

Determine if the element specified by the condition exists in the list.

Determine if l contains a certain element:

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

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

Output all elements that meet the specified conditions.

Filter out elements with the specified length3The elements:

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

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

Check all elements.

For example: Determine if all elements start with "H":

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

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

Apply the function to all elements of the list

20

def head: A

Get the first element of the list

21

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

From the specified position from Start to find the first occurrence position of the element

22

def init: List[A]

Return all elements except the last one

23

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

Calculate the intersection of multiple sets

24

def isEmpty: Boolean

Check if the list is empty

25

def iterator: Iterator[A]

Create a new iterator to iterate over the elements

26

def last: A

Return the last element

27

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

Find the last occurrence position of the element at the specified position end

28

def length: Int

Return the length of the list

29

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

Recalculate all elements by the given method

30

def max: A

Find the maximum element

31

def min: A

Find the minimum element

32

def mkString: String

Display all elements of the list as a string

33

def mkString(sep: String): String

Display all elements of the list as a string using a delimiter

34

def reverse: List[A]

List Reversal

35

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

List Sorting

36

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

Check if the list contains the specified sequence at the specified position

37

def sum: A

Calculate the sum of the elements in the collection

38

def tail: List[A]

Return all elements except the first

39

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

Extract the first n elements of the list

40

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

Extract the last n elements of the list

41

def toArray: Array[A]

List to Array Conversion

42

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

Return a buffer that contains all elements of the list

43

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

List to Map Conversion

44

def toSeq: Seq[A]

List to Seq Conversion

45

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

List to Set Conversion

46

def toString(): String

List to String Conversion

More methods can be referred to API Documentation

Scala Collections