Easy Tutorial
❮ Scala While Loop Scala Loop Types ❯

Scala List

Scala Collections

Scala lists are similar to arrays in that all elements have the same type, but they also have differences: lists are immutable, meaning their values cannot be changed once defined, and secondly, lists have a recursive structure (i.e., 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 of various types are shown:

Examples

// String list
val site: List[String] = List("tutorialpro", "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 ::

Nil can also represent an empty list.

The above examples can be written as follows:

Examples

// String list
val site = "tutorialpro" :: ("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:

Any operation on a Scala list can be expressed using these three basic operations. Examples are as follows:

Examples

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

    println( "First site is : " + site.head )
    println( "Last site is : " + site.tail )
    println( "Check if list site is empty : " + site.isEmpty )
    println( "Check if nums is empty : " + nums.isEmpty )
  }
}

Executing the above code, the output results are:

$ vim Test.scala 
$ scala Test.scala 
First site is : tutorialpro
Last site is : List(Google, Baidu)
Check if list site is empty : false
Check if nums is empty : true

Connecting Lists

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

Examples

object Test {
  def main(args: Array[String]) {
    val site1 = "tutorialpro" :: ("Google" :: ("Baidu" :: Nil))
    val site2 = "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  )
  }
}

Executing the above code, the output results are:

$ vim Test.scala 
$ scala Test.scala 
site1 ::: site2 : List(tutorialpro, Google, Baidu, Facebook, Taobao)
site1.:::(site2) : List(Facebook, Taobao, tutorialpro, Google, Baidu)
List.concat(site1, site2) : List(tutorialpro, 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:

Examples

``` object Test { def main(args: Array[String]) { val site = List.fill(3)("tutorialpro") // Repeat tutorialpro 3 times println( "site : " + site  )

val num = List.fill(10)(2)         // Repeat element 2, 10 times
println( "num : "

| 17 | def filter(p: (A) => Boolean): List[A] Outputs all elements that meet the specified condition. Filters elements with a length of 3: scala> l.filter(s => s.length == 3)<br>res8: List[String] = List(Hah, WOW) | | 18 | def forall(p: (A) => Boolean): Boolean Checks all elements. For example: Determines if all elements start with "H": scala> l.forall(s => s.startsWith("H"))<br>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 position of the first occurrence of the 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 if 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 position of the last occurrence of the element starting from the specified position end | | 28 | def length: Int Returns the length of the list | | 29 | def mapB: List[B] Recalculates all elements through the given method | | 30 | def max: A Finds the maximum element | | 31 | def min: A Finds the minimum 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 startsWithB: Boolean Checks if the list contains the specified sequence at the specified position | | 37 | def sum: A Calculates the sum of the elements in the collection | | 38 | def tail: List[A] Returns all elements except the first one | | 39 | def take(n: Int): List[A] Takes the first n elements of the list | | 40 | def takeRight(n: Int): List[A] Takes 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 the List to a Map | | 44 | def toSeq: Seq[A] Converts the List to a Seq | | 45 | def toSet[B >: A]: Set[B] Converts the List to a Set | | 46 | def toString(): String Converts the list to a string |

For more methods, refer to the API documentation.

Scala Collections

❮ Scala While Loop Scala Loop Types ❯