Scala List
Scala lists are similar to arrays in that all their elements have the same type, but they differ: lists are immutable, meaning their values cannot be changed once defined, and lists have a recursive (linked-list) structure, which arrays do not.
The element type T of a list can be written as List[T]. For example, the following lists several types of lists:
Example
// list of strings
val
site
:
List
[
String
]
=
List
(
"Runoob"
,
"Google"
,
"Baidu"
)
// list of integers
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 ::
Nil can also be represented as an empty list.
The above examples can be written as follows:
Example
// list of strings
val
site
=
"Runoob"
::
(
"Google"
::
(
"Baidu"
::
Nil
)
)
// list of integers
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 listtailReturns a list containing all elements except the firstisEmptyReturns true when the list is empty
Any operation on a Scala list can be expressed using these three basic operations. Example as follows:
Example
// list of strings
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
site
=
"Runoob"
::
(
"Google"
::
(
"Baidu"
::
Nil
)
)
val
nums
=
Nil
println
(
"The first website is: "
- site.
head
)
println
(
"The last website is: "
- site.
tail
)
println
(
"Check whether list site is empty: "
- site.
isEmpty
)
println
(
"Check whether nums is empty: "
- nums.
isEmpty
)
}
}
The output of the code above is:
$ vim Test.scala
$ scala Test.scala
第一网站是 : Runoob
最后一个网站是 : List(Google, Baidu)
查看列表 site 是否为空 : false
查看 nums 是否为空 : true
Concatenating Lists
You can use the ::: operator or the List.:::() The method or the List.concat() method to concatenate two or more lists. Example as follows:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
site1
=
"Runoob"
::
(
"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
)
}
}
The output of the code above is:
$ vim Test.scala
$ scala Test.scala
site1 ::: site2 : List(Runoob, Google, Baidu, Facebook, Taobao)
site1.:::(site2) : List(Facebook, Taobao, Runoob, Google, Baidu)
List.concat(site1, site2) : List(Runoob, 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
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
site
=
List.
fill
(
3
)
(
"Runoob"
)
// repeat Runoob 3 times
println
(
"site : "
- site
)
val
num
=
List.
fill
(
10
)
(
2
)
// repeat element 2, 10 times
println
(
"num : "
- num
)
}
}
The output of the code above is:
$ vim Test.scala
$ scala Test.scala
site : List(Runoob, Runoob, Runoob)
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 is a specified function. The value computed by the function is inserted into the list, starting at 0. Example as follows:
Example
object
Test
{
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
)
}
}
The output of the code above 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 is used to reverse the order of a list, example as follows:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
site
=
"Runoob"
::
(
"Google"
::
(
"Baidu"
::
Nil
)
)
println
(
"site before reversal: "
- site
)
println
(
"site after reversal: "
- site.
reverse
)
}
}
The output of the code above is:
$ vim Test.scala
$ scala Test.scala
site 反转前 : List(Runoob, Google, Baidu)
site 反转后 : List(Baidu, Google, Runoob)
Scala List Common Methods
The following table lists the commonly used methods of 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 a specified list at the beginning of the list
| | 4 |def :+(elem: A): List[A]
Returns a copy of the list with the element added.
scala> val a = List(1) a: List[Int] = List(1)| | 5 |scala> val b = a :+ 2 b: List[Int] = List(1, 2)
scala> println(a) List(1)
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
Tests whether the list contains a 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]
Removes duplicate elements from the list and returns a new list
| | 11 |def drop(n: Int): List[A]
Drops the first n elements and returns a new list
| | 12 |def dropRight(n: Int): List[A]
Drops the last n elements and returns a new list
| | 13 |def dropWhile(p: (A) => Boolean): List[A]
Drops elements from left to right until predicate p no longer holds
| | 14 |def endsWith[B](that: Seq[B]): Boolean
Tests whether the list ends with a specified sequence
| | 15 |def equals(that: Any): Boolean
Tests for equality
| | 16 |def exists(p: (A) => Boolean): Boolean
Determines whether elements satisfying a specified condition exist in the list.
Determines whether 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 satisfy the specified condition.
Filters out elements of length 3:
scala> l.filter(s => s.length == 3) res8: List[String] = List(Hah, WOW)| | 18 |
def forall(p: (A) => Boolean): Boolean
Tests all elements.
For example: check 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 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]
Computes the intersection of multiple collections
| | 24 |def isEmpty: Boolean
Tests 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 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]
Recomputes all elements using the given method
| | 30 |def max: A
Finding 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
Tests whether the list contains a specified sequence at a given position
| | 37 |def sum: A
Computes the sum of the collection's 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 a List to a Map
| | 44 |def toSeq: Seq[A]
Converts a List to a Seq
| | 45 |def toSet[B >: A]: Set[B]
Converts a List to a Set
| | 46 |def toString(): String
Converts the list to a string
|For more methods, refer to API Documentation
Scala Collections