Scala – Lists

  • Post category:Scala
  • Reading time:11 mins read

Scala List

In this post we will understand what is Scala List with examples. Scala Lists are similar to arrays but there are two important differences.

  • First, lists are immutable, which means elements of a list cannot be changed by assignment.
  • Second, lists represent a linked list whereas arrays are flat.

Different ways to create a List in Scala

  1. Lisp style
  2. Java style
  3. Using the List class range method
  4. Using the List class fill method
  5. Using the List class tabulate method

Examples of creating a List

// Create List LISP style. This creates a List that contains the integers 1, 2, and 3. With this approach, // we need to end the list with the Nil object.
scala> val list = 1 :: 2 :: 3 :: Nil
list: List[Int] = List(1, 2, 3)

// Java-style. This syntax looks a lot like the Java way to create an object, except that we don't need the // "new" keyword before the List and we also don't have to declare the type of elements in the List.
val list = List(1,2,3)

// List of Strings. 
val fruits = List("Apple", "Banana", "Mango") 

// Empty List. 
val empty: List[Nothing] = List()

// Mixing the types in a List.
scala> val numbers = List[Number](1, 2.0, 33d, 0x1) 
numbers: List[java.lang.Number] = List(1, 2.0, 33.0, 1)

Example of creating List – ‘range’ method

scala> val num = List.range(1, 6) 
num: List[Int] = List(1, 2, 3, 4, 5)

We can create a List is with the range method. Above example creates a List of Int values, beginning at 1, and ending at 5. We can also create a list using range method that takes a third argument, which serves as a “step” value when creating the List

scala> val num = List.range(0, 6, 2) 
x: List[Int] = List(0, 2, 4)

Example of creating List – ‘fill’ method

We can create a List using using Scala List's fill method. All elements of the List will have the predefined value.
scala> val list = List.fill(5)("Proedu") 
list: List[java.lang.String] = List(Proedu, Proedu, Proedu, Proedu, Proedu)

Example of creating List – ‘tabulate’ method

We can create a List using using Scala List’s tabulate method.The tabulate method creates a new List whose elements are created according to the function we supply. In the below example we have created a List of five elements, where the element values are the addition of the index of each element, so 0 becomes 0, 1 becomes 2, 2 becomes 4, 3 becomes 6, and 4 becomes 8.

scala> val nums = List.tabulate(5)(n => n + n) 
nums: List[Int] = List(0, 2, 4, 6, 8)

Example – Concatenating Lists

We can use either ::: operator or List.:::() method or List.concat() method to add two or more lists.

object Demo {
   def main(args: Array[String]) {
      val a = List(1, 2, 3) 
      val b = List(4, 5, 6) 
      
      // Java Style
      val c = List.concat(a, b) 
      println(c)

      // LISP style
      val d = a ::: b 
      println(d)
   }
}

// Output
List(1, 2, 3, 4, 5, 6)
List(1, 2, 3, 4, 5, 6)

Example – Reverse a List’s Order

List.reverse method to reverse all elements of the list.

val fruit = "Apple" :: "Banana" :: "Grapes" :: Nil

println("Original Lit : " + fruit)
println("After reverse fruit : " + fruit.reverse)

// Output
Before reverse fruit : List(Apple, Banana, Grapes)
After reverse fruit : List(Grapes, Banana, Apple)

Important methods present in List Class

Below table presents the important List methodsFor a complete list of methods available, please check the official documentation of Scala.

Sr.NoMethods with Description
1def +(elem: A): List[A]Prepends an element to this list
2def ::(x: A): List[A]Adds an element at the beginning of this list.
3def :::(prefix: List[A]): List[A]Adds the elements of a given list in front of this list.
4def ::(x: A): List[A]Adds an element x at the beginning of the list
5def addString(b: StringBuilder): StringBuilderAppends all elements of the list to a string builder.
6def addString(b: StringBuilder, sep: String): StringBuilderAppends all elements of the list to a string builder using a separator string.
7def apply(n: Int): ASelects an element by its index in the list.
8def contains(elem: Any): BooleanTests whether the list contains a given value as an element.
9def copyToArray(xs: Array[A], start: Int, len: Int): UnitCopies elements of the list to an array. Fills the given array xs with at most length (len) elements of this list, beginning at position start.
10def distinct: List[A]Builds a new list from the list without any duplicate elements.
11def drop(n: Int): List[A]Returns all elements except first n ones.
12def dropRight(n: Int): List[A]Returns all elements except last n ones.
13def dropWhile(p: (A) => Boolean): List[A]Drops longest prefix of elements that satisfy a predicate.
14def endsWith[B](that: Seq[B]): BooleanTests whether the list ends with the given sequence.
15def equals(that: Any): BooleanThe equals method for arbitrary sequences. Compares this sequence to some other object.
16def exists(p: (A) => Boolean): BooleanTests whether a predicate holds for some of the elements of the list.
17def filter(p: (A) => Boolean): List[A]Returns all elements of the list which satisfy a predicate.
18def forall(p: (A) => Boolean): BooleanTests whether a predicate holds for all elements of the list.
19def foreach(f: (A) => Unit): UnitApplies a function f to all elements of the list.
20def head: ASelects the first element of the list.
21def indexOf(elem: A, from: Int): IntFinds index of first occurrence value in the list, after the index position.
22def init: List[A]Returns all elements except the last.
23def intersect(that: Seq[A]): List[A]Computes the multiset intersection between the list and another sequence.
24def isEmpty: BooleanTests whether the list is empty.
25def iterator: Iterator[A]Creates a new iterator over all elements contained in the iterable object.
26def last: AReturns the last element.
27def lastIndexOf(elem: A, end: Int): IntFinds index of last occurrence of some value in the list; before or at a given end index.
28def length: IntReturns the length of the list.
29def map[B](f: (A) => B): List[B]Builds a new collection by applying a function to all elements of this list.
30def max: AFinds the largest element.
31def min: AFinds the smallest element.
32def mkString: StringDisplays all elements of the list in a string.
33def mkString(sep: String): StringDisplays all elements of the list in a string using a separator string.
34def reverse: List[A]Returns new list with elements in reversed order.
35def sorted[B >: A]: List[A]Sorts the list according to an Ordering.
36def startsWith[B](that: Seq[B], offset: Int): BooleanTests whether the list contains the given sequence at a given index.
37def sum: ASums up the elements of this collection.
38def tail: List[A]Returns all elements except the first.
39def take(n: Int): List[A]Returns first “n” elements.
40def takeRight(n: Int): List[A]Returns last “n” elements.
41def toArray: Array[A]Converts the list to an array.
42def toBuffer[B >: A]: Buffer[B]Converts the list to a mutable buffer.
43def toMap[T, U]: Map[T, U]Converts this list to a map.
44def toSeq: Seq[A]Converts the list to a sequence.
45def toSet[B >: A]: Set[B]Converts the list to a set.
46def toString(): StringConverts the list to a string.

Happy Learning 🙂