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