Scala List
Scala lists are similar to arrays in that all elements have the same type, but they are also different: lists are immutable, meaning once a value is defined it cannot be changed, and lists have a recursive structure (i.e., a linked list structure) whereas arrays do not.
The element type T of a list can be written as List[T]. For example, the following lists various types of lists:
Example
val site: List[String] = List("Example", "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 a list are Nil and ::Niland::
NilIt can also be represented as an empty list.
The above example can be written as follows:
Example
val site = "Example" :: ("Google" :: ("Baidu" :: Nil))
// Integer list
val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
// Empty list
val empty = Nil
// Two-dimensional list
val dim = (1 :: (0 :: (0 :: Nil))) ::
(0 :: (1 :: (0 :: Nil))) ::
(0 :: (0 :: (1 :: Nil))) :: Nil
Basic List Operations
Scala lists have three basic operations:
-
headReturns the first element of the list -
tailReturns a list containing all elements except the first -
isEmptyReturns true when the list is empty
Any operation on Scala lists can be expressed using these three basic operations. Examples are as follows:
Example
object Test {
def main(args: Array[String]) {
val site = "Example" :: ("Google" :: ("Baidu" :: Nil))
val nums = Nil
println( "The first website is: " + site.head )
println( "The last website is: " + site.tail )
println( "Check if the list site is empty: " + site.isEmpty )
println( "Check if nums is empty: " + nums.isEmpty )
}
}
Executing the above code produces the following output:
$ vim Test.scala $ scala Test.scala 第一网站是 : Example 最后一个网站是 : List(Google, Baidu) 查看列表 site 是否为空 : false 查看 nums 是否为空 : true
Concatenating Lists
You can use the:::::: operator or theList.:::()List.:::() method or theList.concat()concat method to concatenate two or more lists. Examples are as follows:
Example
def main(args: Array[String]) {
val site1 = "Example" :: ("Google" :: ("Baidu" :: Nil))
val site2 = "Facebook" :: ("Taobao" :: Nil)
// Using the ::: operator
var fruit = site1 ::: site2
println( "site1 ::: site2 : " + fruit )
// Using the List.:::() method
fruit = site1.:::(site2)
println( "site1.:::(site2) : " + fruit )
// Using the concat method
fruit = List.concat(site1, site2)
println( "List.concat(site1, site2) : " + fruit )
}
}
Executing the above code produces the following output:
$ vim Test.scala $ scala Test.scala site1 ::: site2 : List(Example, Google, Baidu, Facebook, Taobao) site1.:::(site2) : List(Facebook, Taobao, Example, Google, Baidu) List.concat(site1, site2) : List(Example, Google, Baidu, Facebook, Taobao)
List.fill()
We can use the List.fill() method to create a list with a specified number of repeated elements:
Example
def main(args: Array[String]) {
val site = List.fill(3)("Example") // Repeat Example 3 times
println( "site : " + site )
val num = List.fill(10)(2) // Repeat element 2, 10 times
println( "num : " + num )
}
}
Executing the above code produces the following output:
$ vim Test.scala $ scala Test.scala site : List(Example, Example, Example) num : List(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
List.tabulate()
The List.tabulate() method creates a list using 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 using the specified function and insert the returned value into the list, starting from 0. Examples are as follows:Example
def main(args: Array[String]) {
// Create 5 elements using the given function
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 )
}
}
Executing the above code produces the following output:
$ 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 is used to reverse the order of a list. Examples are as follows:
Example
def main(args: Array[String]) {
val site = "Example" :: ("Google" :: ("Baidu" :: Nil))
println( "Before site reversal: " + site )
println( "After site reversal: " + site.reverse )
}
}
Executing the above code produces the following output:
$ vim Test.scala $ scala Test.scala site 反转前 : List(Example, Google, Baidu) site 反转后 : List(Baidu, Google, Example)
Scala List Common Methods
The following table lists common methods for Scala List:
| No. | Method and Description |
|---|---|
| 1 |
def +:(elem: A): List[A] Prepends an element 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] Adds an element at the beginning of the list |
| 3 |
def :::(prefix: List[A]): List[A] Adds elements of the specified list at the beginning of the list |
| 4 |
def :+(elem: A): List[A] Copies 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 Adds all elements of the list to a StringBuilder |
| 6 |
def addString(b: StringBuilder, sep: String): StringBuilder Adds all elements of the list to a StringBuilder with a specified separator |
| 7 |
def apply(n: Int): A Gets an element by list index |
| 8 |
def contains(elem: Any): Boolean Checks whether the list contains the specified element |
| 9 |
def copyToArray(xs: Array[A], start: Int, len: Int): Unit Copies the elements of the list to an array |
| 10 |
def distinct: List[A] Removes duplicate elements from the list and returns a new list |
| 11 |
def drop(n: Int): List[A] Discards the first n elements and returns a new list |
| 12 |
def dropRight(n: Int): List[A] Discards the last n elements and returns a new list |
| 13 |
def dropWhile(p: (A) => Boolean): List[A] Discards elements from left to right until condition p is not satisfied |
| 14 |
def endsWith[B](that: Seq[B]): Boolean Checks whether the list ends with the specified sequence |
| 15 |
def equals(that: Any): Boolean Determines whether they are equal |
| 16 |
def exists(p: (A) => Boolean): Boolean Checks whether an element satisfying the specified condition exists in the list Checks whether list l contains a certain element scala> l.exists(s => s == "Hah") res7: Boolean = true |
| 17 |
def filter(p: (A) => Boolean): List[A] Outputs all elements that meet the specified condition Filters out elements with length 3 scala> l.filter(s => s.length == 3) res8: List[String] = List(Hah, WOW) |
| 18 |
def forall(p: (A) => Boolean): Boolean Checks all elements For example: checks whether all elements start with "H" scala> l.forall(s => s.startsWith("H")) res10: Boolean = false |
| 19 |
def foreach(f: (A) => Unit): Unit Applies a function to all elements of the list |
| 20 |
def head: A Gets the first element of the list |
| 21 |
def indexOf(elem: A, from: Int): Int Finds the first occurrence position of an element starting from the specified position 'from' |
| 22 |
def init: List[A] Returns all elements except the last one |
| 23 |
def intersect(that: Seq[A]): List[A] Calculates the intersection of multiple collections |
| 24 |
def isEmpty: Boolean Checks whether the list is empty |
| 25 |
def iterator: Iterator[A] Creates a new iterator to iterate over the elements |
| 26 |
def last: A Returns the last element |
| 27 |
def lastIndexOf(elem: A, end: Int): Int Finds the last occurrence position of an element starting from the specified position 'end' |
| 28 |
def length: Int Returns the length of the list |
| 29 |
def map[B](f: (A) => B): List[B] Recalculates all elements using the given method |
| 30 |
def max: A Finds the largest element |
| 31 |
def min: A Finds the smallest element |
| 32 |
def mkString: String Displays all elements of the list as a string |
| 33 |
def mkString(sep: String): String Displays all elements of the list as a string using a separator |
| 34 |
def reverse: List[A] Reverses the list |
| 35 |
def sorted[B >: A]: List[A] Sorts the list |
| 36 |
def startsWith[B](that: Seq[B], offset: Int): Boolean Checks whether the list contains the specified sequence at the specified position |
| 37 |
def sum: A Calculates the sum of collection elements |
| 38 |
def tail: List[A] Returns all elements except the first |
| 39 |
def take(n: Int): List[A] Extracts the first n elements of the list |
| 40 |
def takeRight(n: Int): List[A] Extracts the last n elements of the list |
| 41 |
def toArray: Array[A] Converts the list to an array |
| 42 |
def toBuffer[B >: A]: Buffer[B] Returns a buffer containing all elements of the list |
| 43 |
def toMap[T, U]: Map[T, U] Converts List to Map |
| 44 |
def toSeq: Seq[A] Converts List to Seq |
| 45 |
def toSet[B >: A]: Set[B] Converts List to Set |
| 46 |
def toString(): String Converts the list to a string |
For more methods, please refer to theAPI documentation
Other Extensions
Scala Collections