Learn Scala List with Different Methods and Examples

1. Scala List – Objective

In Scala, we have 6 kinds of collections. These are lists, sets, maps, tuples, options, and iterators. In this tutorial on Scala list, we will focus on Lists. We will learn to declare a Scala list, Creating Uniform List, Methods on a Scala list, Operations on a Scala list, Reversing a List in Scala Collections, Defining List using:: Nil, Tabulating a Function, Concatenating Scala list.

So, let’s start learning Scala Lists.

Learn Scala List with Different Methods and Examples

Learn Scala List with Different Methods and Examples

2. Introduction of List in Scala Collections

A collection holds things. This can be strict or lazy(don’t consume memory until accessed). This can also be mutable(reassignable) or immutable. In this tutorial, we will discuss Lists. Next, we’ll look at Sets. Let’s begin.

A list of Scala Collections is much like a Scala array. Except that, it is immutable and represents a linked list. An Array, on the other hand, is flat and mutable. Here’s an Array:

scala> var a=Array(1,2,'a')
a: Array[Int] = Array(1, 2, 97)
scala> a(2)
res3: Int = 97
scala> a(2)=98
scala> a
res5: Array[Int] = Array(1, 2, 98)

3. Declaring a Scala List

Now, here’s a Scala list to compare that to:

scala> var a=List(1,2,'a')
a: List[Int] = List(1, 2, 97)
scala> a(2)
res8: Int = 97
scala> a(3)=98
<console>:13: error: value update is not a member of List[Int]
      a(3)=98
      ^
scala> a=List(1,2,"Ayushi",true)
a: List[Any] = List(1, 2, Ayushi, true)

While declaring a Scala list, we can also denote the type of elements it will hold. If it’ll hold more than one kind, we use ‘Any’. Here are few examples.

scala> val a:List[Int]=List(1,3,2)
a: List[Int] = List(1, 3, 2)
scala> val b:List[Char]=List('a','c','b')
b: List[Char] = List(a, c, b)
scala> val c:List[String]=List("Ayushi","Megha")
c: List[String] = List(Ayushi, Megha)
scala> val d:List[Nothing]=List()
d: List[Nothing] = List()
scala> val e:List[List[Int]]=List(List(1,2,3),List(4,5,6),List(7,8,9))
e: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))

4. Defining Scala List using :: and Nil

Think of Nil as an empty list, and :: as cons. If we had to define the above lists this way, we’d:

scala> val a=1::(2::("Ayushi"::(true::Nil)))
a: List[Any] = List(1, 2, Ayushi, true)
scala> val a=1::2::3::Nil
a: List[Int] = List(1, 2, 3)
scala> val b='a'::('c'::('b'::Nil))
b: List[Char] = List(a, c, b)
scala> val c="Ayushi"::("Megha"::Nil)
c: List[String] = List(Ayushi, Megha)
scala> val d=Nil
d: scala.collection.immutable.Nil.type = List()
scala> val  e=(1::(2::(3::Nil)))::(4::(5::(6::Nil)))::(7::(8::(9::Nil)))::Nil
e: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))

5. Operations on Lists in Scala

We can carry out three operations on a Scala list to get a result:

a. head

This returns the first element of a Scala list.

scala> e.head
res12: List[Int] = List(1, 2, 3)
scala> b.head
res13: Char = a

b. tail

This returns the last element of a Scala list.

scala> c.tail
res14: List[String] = List(Megha)

c. isEmpty

If the list is empty, this returns a Boolean true; otherwise, false.

scala> d.isEmpty
res15: Boolean = true
scala> a.isEmpty
res16: Boolean = false

6. Concatenating Lists in Scala

We can join or concatenate two Scala lists in one of three ways. Let’s take two lists for this:

scala> val a=List(1,2,3)
a: List[Int] = List(1, 2, 3)
scala> val b=List(4,5,6)
b: List[Int] = List(4, 5, 6)

a. The ::: Operator

scala> a:::b
res0: List[Int] = List(1, 2, 3, 4, 5, 6)

b. The List.:::() Method

We can call the :::() method on the first list.

scala> a.:::(b)
res2: List[Int] = List(4, 5, 6, 1, 2, 3)
scala> a
res3: List[Int] = List(1, 2, 3)

c. The List.concat() Method

We can also call the concat() method on List in Scala Collections. We pass both the lists as arguments.

scala> List.concat(a,b)
res5: List[Int] = List(1, 2, 3, 4, 5, 6)

Read: Scala Operators with Syntax and Examples

7. Creating Uniform Lists in Scala

The method List.fill() creates a list and fills it with zero or more copies of an element.

scala> val f=List.fill(7)(1)
f: List[Int] = List(1, 1, 1, 1, 1, 1, 1)

This fills the list with seven instances of the integer 1.

8. Tabulating a Function

Using the List.tabulate() method with a function, we can tabulate a Scala list. The first argument specifies the dimensions; the second describes the elements(computed from a function).

scala> val g=List.tabulate(7)(n=>n*2)
g: List[Int] = List(0, 2, 4, 6, 8, 10, 12)

We can also pass more than one size argument:

scala> val h=List.tabulate(3,7)(_*_)
h: List[List[Int]] = List(List(0, 0, 0, 0, 0, 0, 0), List(0, 1, 2, 3, 4, 5, 6), List(0, 2, 4, 6, 8, 10, 12))

This made a Scala List holding three Lists of lengths 7 each.

scala> val i=List.tabulate(7,5)(_*_)
i: List[List[Int]] = 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(0, 4, 8, 12, 16), List(0, 5, 10, 15, 20), List(0, 6, 12, 18, 24))

You can see that this creates a List holding 7 Lists each holding 5 elements. These are tables of integers from 0 up.
Read: Scala Functions with Syntax and Examples

9. Reversing a Scala List

This reverses the order of elements in a list using the List.reverse method.

scala> a
res6: List[Int] = List(1, 2, 3)
scala> a.reverse
res7: List[Int] = List(3, 2, 1)
scala> a
res8: List[Int] = List(1, 2, 3)
Scala Quiz

10. Methods on a List in Scala

We can call the following methods on a Scala List: (Note that these don’t modify the Lists)

a. def +(elem: A): List[A]

This postpends an element to the Scala list.

scala> a.+("2")
res86: String = List(1, 2, 3)2

b. def :::(prefix: List[A]): List[A]
This joins the List in the argument to the other List.

scala> a.:::(List(7,8,9))
res16: List[Int] = List(7, 8, 9, 1, 2, 3)

c. def ::(x: A): List[A]
This adds an element to a List’s beginning.

scala> a.::("2")
res17: List[Any] = List(2, 1, 2, 3)

d. def addString(b: StringBuilder): StringBuilder
This appends all elements of a Scala list to a String Builder.

scala> var b=new StringBuilder()
b: StringBuilder =
scala> a.addString(b)
res19: StringBuilder = 123
scala> a
res20: List[Int] = List(1, 2, 3)
scala> b
res21: StringBuilder = 123

e. def addString(b: StringBuilder, sep: String): StringBuilder
This does the same thing, except with a separator between the elements.
Let’s first reset b to an empty string.

scala> b=new StringBuilder()
b: StringBuilder =
scala> a.addString(b,"*")
res23: StringBuilder = 1*2*3

Read: Scala Data Types
f. def apply(n: Int): A
This selects an element in the Scala List by its index.

scala> a.apply(2)
res24: Int = 3

g. def contains(elem: Any): Boolean
If the list contains a certain element, this returns true; otherwise, false.

scala> a.contains(2)
res25: Boolean = true
scala> a.contains(4)
res26: Boolean = false

h. def copyToArray(xs: Array[A], start: Int, len: Int): Unit
This copies the elements of a List to an Array. Start decides where to write, and len decides the length of elements to copy.

Join DataFlair on Telegram
scala> var arr=Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
arr: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
scala>  a.copyToArray(arr,2,3)
scala> arr
res42: Array[Int] = Array(0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

Let’s try changing the length to 2.

scala> var arr=Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
arr: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
scala> a.copyToArray(arr,2,2)
scala> arr
res44: Array[Int] = Array(0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

i. def distinct: List[A]
Let’s take a new Scala List for this.

scala> var j=List(1,1,4,1,3,2,1)
j: List[Int] = List(1, 1, 4, 1, 3, 2, 1)

Distinct returns a new List without duplicates.

scala> j.distinct
res46: List[Int] = List(1, 4, 3, 2)

j. def drop(n: Int): List[A]
This returns all elements except the first n.

scala> j.drop(2)
res47: List[Int] = List(4, 1, 3, 2, 1)

k. def dropRight(n: Int): List[A]
This returns all elements except the last n.

scala> j.dropRight(2)
res48: List[Int] = List(1, 1, 4, 1, 3)

Read Scala String: Creating String, Concatenation, String Length
l. def dropWhile(p: (A) => Boolean): List[A]
This drops the longest prefix of elements that satisfy the predicate.

scala> j.dropWhile(x=>{x%2!=0})
res52: List[Int] = List(4, 1, 3, 2, 1)

This dropped the elements 1 and 1. Then it stopped at 4 because it doesn’t satisfy the predicate.
m. def equals(that: Any): Boolean
This compares two sequences.

scala> a.equals(b)
res53: Boolean = false
scala> a.equals(List(1,2,3))
res55: Boolean = true
n. def exists(p: (A) => Boolean): Boolean

This returns true if a predicate holds true for any value in the Scala  List.

scala> a.exists(x=>{x%2!=0})
res56: Boolean = true
o. def filter(p: (A) => Boolean): List[A]

This returns all such values.

scala> a.filter(x=>{x%2!=0})
res57: List[Int] = List(1, 3)

p. def forall (p: (a) => Boolean) : Boolean
This returns true if the predicate holds true for all values in the List.

scala> a.forall(x=>{x%2!=0})
res58: Boolean = false

q. def indexOf(elem: A, from: Int): Int
This returns the index of the first occurrence of the element in the List.

scala> a.indexOf(2)
res61: Int = 1

r. def init: List[A]
This returns all elements except the last.

scala> a.init
res62: List[Int] = List(1, 2)

s. def iterator: Iterator[A]
This creates an iterator over the Scala List.

scala> a.iterator
res63: Iterator[Int] = non-empty iterator

t. def lastIndexOf(elem: A, end: Int): Int
This returns the index of the last occurrence of an element, before or at given index.

scala> List(1,2,1,2,1).lastIndexOf(2)
res64: Int = 3

u. def length: Int
This returns a List’s length.

scala> a.length
res65: Int = 3

v. def map[B](f: (A) => B): List[B]
This applies the function to every element in the list.

scala> a.map(x=>x*x)
res66: List[Int] = List(1, 4, 9)

w. def max: A
This returns the highest element.

scala> a.max
res67: Int = 3

x. def min: A
This returns the lowest element.

scala> a.min
res68: Int = 1

y. def mkString: String
This displays all elements of a list in a String.

scala> a.mkString
res69: String = 123

z. def mkString(sep: String): String
This lets us define a separator for mkString.

scala> a.mkString("*")
res71: String = 1*2*3

aa. def reverse: List[A]
This reverses a List of Scala Collections.

scala> a.reverse
res72: List[Int] = List(3, 2, 1)

ab. def sum: A
This returns the sum of all elements.

scala> a.sum
res74: Int = 6

ac. def take(n: Int): List[A]
This returns the first n elements.

scala> a.take(2)
res75: List[Int] = List(1, 2)

ad. def takeRight(n: Int): List[A]
This returns the last n elements.

scala> a.takeRight(2)
res76: List[Int] = List(2, 3)

ae. def toArray: Array[A]
This returns an Array from a List.

scala> a.toArray
res78: Array[Int] = Array(1, 2, 3)

af. def toBuffer[B >: A]: Buffer[B]
This returns a Buffer from a Scala List.

scala> a.toBuffer
res79: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3)

ag. def toSeq: Seq[A]
This returns a Seq from a List.

scala> a.toSeq
res81: scala.collection.immutable.Seq[Int] = List(1, 2, 3)

ah. def toSet[B >: A]: Set[B]
This returns a Set from a List.

scala> a.toSet
res82: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

ai. def toString(): String
This returns a String from a List.

scala> a.toString
res83: String = List(1, 2, 3)

This was all about Scala List. Hope you like our explanation.

11. Conclusion

This is all about Scala List. Stay tuned for tutorials on other kinds of collections like Sets and Maps. Furthermore, if you have any query, feel free to ask in the comment section.
For reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.