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,

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

Fundamental methods of List in Scala

list.headReturns first element of the list
list.tailIt will remove head element and returns the rest of the list
list.isEmptyChecks whether the list is empty or not
value :: listAdds new value to as a new head in list

Let’s have some examples on List,

Scala List : Basic operations code example


Useful methods of List in Scala

list.lengthReturns size of list
list.lastReturns last element of the list
list.distinctReturns list after removing duplicated records
list.reverseReturns list in reverse order
list.mkStringReturns 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.initReturns list after removing last element
listOne ::: listOtherReturns new list after joining two lists
nestedList.flattenReturns a flat list created from the nested list

Some more examples on List,

Scala List : Widely used operation by code example

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.