Scala Collections
Scala lists are similar to arrays in that all elements are of the same type, but they also differ: lists are immutable, meaning once a value is defined it cannot be changed, and secondly, 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. For example, the following lists various types of lists:
## Example
// String list
val site: List= List("Tutorial", "Google", "Baidu")
// Integer list
val nums: List= List(1, 2, 3, 4)
// Empty list
val empty: List= List()
// Two-dimensional list
val dim: List[List]=
List(
List(1, 0, 0),
List(0, 1, 0),
List(0, 0, 1)
)
The two basic units for constructing a list are **Nil** and **::**
**Nil** can also represent an empty list.
The above examples can be written as follows:
## Example
// String list
val site ="Tutorial"::("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:
* `head` returns the first element of the list
* `tail` returns a list consisting of all elements except the first
* `isEmpty` returns true when the list is empty
Any operation on Scala lists can be expressed using these three basic operations. Examples are as follows:
## Example
// String list
object Test {
def main(args: Array){
val site ="Tutorial"::("Google"::("Baidu":: Nil))
val nums = Nil
println("First website is : " + site.head)
println("Last website is : " + site.tail)
println("Check if site list 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 First website is : TutorialLast website is : List(Google, Baidu)Check if site list is empty : falseCheck if nums is empty : true
* * *
## Concatenating Lists
You can use the **:::** operator or **List.:::()** method or **List.concat()** method to concatenate two or more lists. Examples are as follows:
## Example
object Test {
def main(args: Array){
val site1 ="Tutorial"::("Google"::("Baidu":: Nil))
val site2 ="Facebook"::("Taobao":: Nil)
// Use ::: operator
var fruit = site1 ::: site2
println("site1 ::: site2 : " + fruit )
// Use List.:::() method
fruit = site1.:::(site2)
println("site1.:::(site2) : " + fruit )
// Use 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(Tutorial, Google, Baidu, Facebook, Taobao) site1.:::(site2) : List(Facebook, Taobao, Tutorial, Google, Baidu)List.concat(site1, site2) : List(Tutorial, 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:
## Example
object Test {
def main(args: Array){
val site = List.fill(3)("Tutorial")// Repeat Tutorial 3 times
println("site : " + site )
val num = List.fill(10)(2)// Repeat element 2, 10 times
println("num : " + num )
}
}
Execute the above code, the output result is:
$ vim Test.scala $ scala Test.scala site : List(Tutorial, Tutorial, Tutorial) 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, and the second parameter is the specified function. We calculate the result through the specified function and return the value to be inserted into the list, with a starting value of 0. Examples are as follows:
## Example
object Test {
def main(args: Array){
// Create 5 elements through 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 )
}
}
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 the list, as shown in the following example:
## Example
object Test {
def main(args: Array){
val site ="Tutorial"::("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(Tutorial, Google, Baidu) site after reversal : List(Baidu, Google, Tutorial)
* * *
## Common Scala List Methods
The following table lists the commonly used methods for Scala List:
| No. | Method & Description |
| --- | --- |
| 1 | **def +:(elem: A): List** Prepends an element to the list scala> val x = List(1) x: List = List(1) scala> val y = 2 +: x y: List = List(2, 1) scala> println(x)List(1) |
| 2 | **def ::(x: A): List** Adds an element at the beginning of the list |
| 3 | **def :::(prefix: List): List** Adds the elements of a specified list at the beginning of the list |
| 4 | **def :+(elem: A): List** Returns a copy of the list with the element appended. scala> val a = List(1) a: List = List(1) scala> val b = a :+ 2 b: List = 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 its index in the list |
| 8 | **def contains(elem: Any): Boolean** Checks if the list contains a specified element |
| 9 | **def copyToArray(xs: Array, start: Int, len: Int): Unit** Copies elements of the list to an array. |
| 10 | **def distinct: List** Removes duplicate elements from the list and returns a new list |
| 11 | **def drop(n: Int): List** Discards the first n elements and returns a new list |
| 12 | **def dropRight(n: Int): List** Discards the last n elements and returns a new list |
| 13 | **def dropWhile(p: (A) => Boolean): List** Discards elements from left to right until condition p is not met |
| 14 | **def endsWith(that: Seq): Boolean** Checks if the list ends with a specified sequence |
| 15 | **def equals(that: Any): Boolean** Checks if it is equal to another object |
| 16 | **def exists(p: (A) => Boolean): Boolean** Checks if any element in the list satisfies the specified condition. Check if an element exists in l: scala> l.exists(s => s == "Hah") res7: Boolean = true |
| 17 | **def filter(p: (A) => Boolean): List** Outputs all elements that satisfy the specified condition. Filter