Scala Collections : List with Code Examples

After the brief introduction on Scala Collections, let’s move on by looking at the List first. List is the most commonly used collection class in any programming language. List can be used same as Array but the size of list grows dynamically. List in Scala are immutable, defined under scala.collection.immutable package and if you want to use mutable version of List than you can use scala.collection.mutable.MutableList class.

Let’s have a look to some important properties of List,

  • List in Scala can be defined as List[Type]
  • When you create an empty list than type of the list is List[Nothing] (explained in my post related to Scala Data Types by Code Example)

Various syntax for creating list,

List(Element 1, Element 2, ..., ELement N) //List Of N elements
value 1 :: value 2 :: ... :: value N //List Of N elements
List() //An Empty List
Nil //An Empty List
value 1 :: value 2 :: existingList//Adding values to existing list

I think it is enough theory. Now let’s have basic some examples,

//Creating Empty List
var cityList = List()

//Alternate for creating empty List
var cityList = Nil

//Creating List with elements
var cityList = List("Amsterdam", "London", "Paris")

//Appending items to List
var newCityList = "New York" :: "Toronto" :: cityList

Fundamental methods of List in Scala

Method Description
list.head Returns first element of the list
list.tail It will remove head element and returns the rest of the list
list.isEmpty Checks whether the list is empty or not
value :: list Adds new value to as a new head in list

Let’s have some examples on List,

Scala List : Basic operations code example
package com.backtobazics.immutable.list

object BazicOperations {
  def main(args: Array[String]) {
    //Creating List with elements
    val cityList = List("Amsterdam", "London", "Paris")
    println("Head of the list : " + cityList.head)
    //Appending items to List head
    val newCityList = "New York" :: "Toronto" :: cityList
    println("New head of the list : " + newCityList.head)
    println("Tail of the list : " + newCityList.tail)
    println("is List Empty : " + newCityList.isEmpty)

// Execute Command : BazicOperations.main(null)
// Output :
// Head of the list : Amsterdam
// New head of the list : New York
// Tail of the list : List(Toronto, Amsterdam, London, Paris)
// is List Empty : false

Useful methods of List in Scala

Method Description
list.length Returns size of list
list.last Returns last element of the list
list.distinct Returns list after removing duplicated records
list.reverse Returns list in reverse order
list.mkString Returns string created by concatenating all the elements of list
list.mkString(delim) Returns string created by concatenating all the elements (with delimiter in between) of list
list.init Returns list after removing last element
listOne ::: listOther Returns new list after joining two lists
nestedList.flatten Returns a flat list created from the nested list

Some more examples on List,

Scala List : Widely used operation by code example
package com.backtobazics.immutable.list

object ListOperations {
  def main(args: Array[String]) {

    //New list 
    var cityList = List("Amsterdam", "London", "Paris")
    println("cityList : " + cityList)
    println("cityList in reverse order : " + cityList.reverse)

    //Appending same list in reverse order
    cityList = cityList ::: cityList.reverse
    println("cityList reverse append: " + cityList)
    println("cityList last element: " + cityList.last)
    //Adding new elements to head
    cityList = "New York" :: "Toronto" :: cityList
    println("cityList append to head: " + cityList)

    //Removing duplicates
    cityList = cityList.distinct
    println("cityList Removing duplicates: " + cityList)

    //print all elements after removing last element
    for (e <- cityList.init) println("Element : " + e)

// Output : 
// cityList : List(Amsterdam, London, Paris)
// cityList in reverse order : List(Paris, London, Amsterdam)
// cityList reverse append: List(Amsterdam, London, Paris, Paris, London, Amsterdam)
// cityList last element: Amsterdam
// cityList append to head: List(New York, Toronto, Amsterdam, London, Paris, Paris, London, Amsterdam)
// cityList Removing duplicates: List(New York, Toronto, Amsterdam, London, Paris)
// Element : New York
// Element : Toronto
// Element : Amsterdam
// Element : London
package com.backtobazics.immutable.list

object ListOperations2 {
  def main(args: Array[String]) {
    //Matrix using List
    var matrix = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
    println("Print Matrix")
    for (i <- matrix) {
      for (j <- i) {
        print(" " + j)
    var flatList = matrix.flatten
    //Transfer all values to a single list
    println("Flat list : " + flatList)
    var strMatrixList = flatList.mkString(", ")
    //Create a string of comma separated list values 
    println("CSV String : " + strMatrixList)

// Output
// Print Matrix
//  1 2 3
//  4 5 6
//  7 8 9
// Flat list : List(1, 2, 3, 4, 5, 6, 7, 8, 9)
// CSV String : 1, 2, 3, 4, 5, 6, 7, 8, 9

Similar to List you can use scala.collection.immutable.Set class for various set operation. This class mostly has same methods as List with property that it can contain only unique values. Refer to API doc for more details.


Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>