Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

List all

Scala's List collection is a fundamental data structure in the Scala standard library, providing a wide range of functions for creating, transforming, querying, and manipulating lists. Here is a comprehensive overview of the most common functions available for List in Scala:

Creating Lists

  • apply: Creates a list from the given elements.

    val list = List(1, 2, 3)
    
  • fill: Creates a list filled with a specified value.

    val list = List.fill(3)("a") // List("a", "a", "a")
    
  • tabulate: Creates a list based on a tabulation function.

    val list = List.tabulate(5)(n => n * n) // List(0, 1, 4, 9, 16)
    
  • range: Creates a list containing a sequence of numbers.

    val list = List.range(1, 5) // List(1, 2, 3, 4)
    

Basic Operations

  • head: Returns the first element.

    val head = list.head
    
  • tail: Returns the list without the first element.

    val tail = list.tail
    
  • isEmpty: Checks if the list is empty.

    val empty = list.isEmpty
    
  • length: Returns the length of the list.

    val length = list.length
    

Adding Elements to a List

  1. Prepending Elements
  • ::: Prepend a single element to the beginning of the list.

    val list = List(1, 2, 3)
    val prependedList = 0 :: list
    println(prependedList) // List(0, 1, 2, 3)
    
  • :::: Prepend another list to the beginning of the list.

    val list1 = List(2, 3, 4)
    val list2 = List(0, 1)
    val combinedList = list2 ::: list1
    println(combinedList) // List(0, 1, 2, 3, 4)
    
  1. Appending Elements
  • :+: Append a single element to the end of the list.

    val list = List(1, 2, 3)
    val appendedList = list :+ 4
    println(appendedList) // List(1, 2, 3, 4)
    
  • ++: Append another list to the end of the list.

    val list1 = List(1, 2, 3)
    val list2 = List(4, 5, 6)
    val combinedList = list1 ++ list2
    println(combinedList) // List(1, 2, 3, 4, 5, 6)
    

ListBuffer Adding and Removing

Because a ListBuffer is mutable the adding and removing can be done on the same instance of the list. All the mutable collection do have these functions
They a located in the Growable trait

Apart from these functions List and ListBuffer do have the same functions This is also valid for: Array, Vector, Seq, Range

import scala.collection.mutable.ListBuffer

val buffer = ListBuffer(1, 2, 3)
  • +=: Appends an element to the buffer.

    buffer += 4 // ListBuffer(1, 2, 3, 4)
    
  • ++=: Appends multiple elements to the buffer.

    buffer ++= Seq(5, 6) // ListBuffer(1, 2, 3, 4, 5, 6)
    
  • -=: Removes an element from the buffer.

    buffer -= 3 // ListBuffer(1, 2, 4, 5, 6)
    
  • --=: Removes multiple elements from the buffer.

    buffer --= Seq(1, 4) // ListBuffer(2, 5, 6)
    
  • clear: Removes all elements from the buffer.

    buffer.clear() // ListBuffer()
    

Element Access

  • apply: Accesses the element at a specific index.

    val elem = list(1)
    
  • indexOf: Finds the index of the first occurrence of an element.

    val index = list.indexOf(2)
    
  • lastIndexOf: Finds the index of the last occurrence of an element.

    val lastIndex = list.lastIndexOf(2)
    

Transformations

  • map: Transforms each element by applying a function.

    val mapped = list.map(_ * 2)
    
  • flatMap: Transforms each element using a function and flattens the result.

    val flatMapped = list.flatMap(x => List(x, x * 2))
    
  • collect: Transforms elements using a partial function.

    val collected = list.collect { case x if x % 2 == 0 => x * 2 }
    

Filtering

  • filter: Selects elements that satisfy a predicate.

    val filtered = list.filter(_ % 2 == 0)
    
  • filterNot: Selects elements that do not satisfy a predicate.

    val filterNot = list.filterNot(_ % 2 == 0)
    
  • partition: Splits the list into two lists based on a predicate.

    val (evens, odds) = list.partition(_ % 2 == 0)
    

Aggregation

  • reduce: Combines elements using a binary function.

    val sum = list.reduce(_ + _)
    
  • fold: Combines elements using a binary function and an initial value.

    val sum = list.fold(0)(_ + _)
    
  • scan: Produces a list of intermediate results.

    val scanSum = list.scan(0)(_ + _)
    

Slicing and Dicing

  • slice: Extracts a sublist from a specified range.

    val sliced = list.slice(1, 3)
    
  • take: Takes the first n elements.

    val taken = list.take(2)
    
  • drop: Drops the first n elements.

    val dropped = list.drop(2)
    
  • splitAt: Splits the list at a specified position.

    val (left, right) = list.splitAt(2)
    
  • takeWhile: Takes elements while a predicate is true.

    val takenWhile = list.takeWhile(_ < 3)
    
  • dropWhile: Drops elements while a predicate is true.

    val droppedWhile = list.dropWhile(_ < 3)
    

Searching

  • exists: Checks if any element satisfies a predicate.

    val hasEven = list.exists(_ % 2 == 0)
    
  • forall: Checks if all elements satisfy a predicate.

    val allEven = list.forall(_ % 2 == 0)
    
  • find: Finds the first element that satisfies a predicate.

    val firstEven = list.find(_ % 2 == 0)
    

Zipping and Unzipping

  • zip: Combines two lists into a list of pairs.

    val zipped = list.zip(List("a", "b", "c"))
    
  • zipWithIndex: Pairs elements with their indices.

    val indexed = list.zipWithIndex
    
  • unzip: Splits a list of pairs into two lists.

    val (numbers, letters) = List((1, 'a'), (2, 'b')).unzip
    

Sorting

  • sorted: Sorts the list.

    val sorted = list.sorted
    
  • sortBy: Sorts the list by a specified function.

    val sortedBy = list.sortBy(-_)
    
  • sortWith: Sorts the list using a comparator function.

    val sortedWith = list.sortWith(_ > _)
    

Grouping

  • groupBy: Groups elements by a specified function.
    val grouped = list.groupBy(_ % 2)
    

Conversion

  • toArray: Converts the list to an array.

    val array = list.toArray
    
  • toSet: Converts the list to a set.

    val set = list.toSet
    
  • mkString: Converts the list to a string with a specified separator.

    val str = list.mkString(", ")
    

Advanced Functions

  • permutations: Returns an iterator of all permutations of the list.

    val perms = list.permutations.toList
    
  • combinations: Returns an iterator of all combinations of the list.

    val combs = list.combinations(2).toList
    
  • sliding: Returns an iterator over sliding windows.

    val windows = list.sliding(2).toList
    

Example Usage

Here are some example usages of the above functions:

val numbers = List(1, 2, 3, 4, 5)

// Basic Operations
val head = numbers.head // 1
val tail = numbers.tail // List(2, 3, 4, 5)
val isEmpty = numbers.isEmpty // false
val length = numbers.size // 5

// Element Access
val elem = numbers(1) // 2
val index = numbers.indexOf(2) // 1

// Transformations
val mapped = numbers.map(_ * 2) // List(2, 4, 6, 8, 10)
val flatMapped = numbers.flatMap(x => List(x, x * 2)) // List(1, 2, 2, 4, 3, 6, 4, 8, 5, 10)

// Filtering
val filtered = numbers.filter(_ % 2 == 0) // List(2, 4)

// Aggregation
val sum = numbers.reduce(_ + _) // 15

// Slicing and Dicing
val sliced = numbers.slice(1, 3) // List(2, 3)
val taken = numbers.take(2) // List(1, 2)
val dropped = numbers.drop(2) // List(3, 4, 5)

// Searching
val hasEven = numbers.exists(_ % 2 == 0) // true

// Zipping and Unzipping
val zipped = numbers.zip(List("a", "b", "c")) // List((1, "a"), (2, "b"), (3, "c"))

// Sorting
val sorted = numbers.sorted // List(1, 2, 3, 4, 5)

// Grouping
val grouped = numbers.groupBy(_ % 2) // Map(1 -> List(1, 3, 5), 0 -> List(2, 4))

// Conversion
val array = numbers.toArray // Array(1, 2, 3, 4, 5)
val set = numbers.toSet // Set(1, 2, 3, 4, 5)
val str = numbers.mkString(", ") // "1, 2, 3, 4, 5"