Scala List Iteration and Filtering

Iterating a scala list is pretty easy and there are many ways of doing it. The choice of which one to use is up to the developer to decide based on the use case and the development guidelines established in the respective projects.

Using Scala For Expression

Scala for expression works well with Lists and is a handy tool.

scala> val listone = List("a","b","c")
listone: List[String] = List(a, b, c)

// For expression. Here i refers to each element of the list
scala> for(i <- listone) {
         println(i)
      }
a
b
c

Using Map function

Scala provide map, flatMap functions for iterating over collections and these works very well with lists.

scala> listone.map(i=>println(i))
a
b
c

The map function can also be used to transform the elements of a list and create a new list. For example

scala> listone.map(x=>"fruits:"+x)
res10: List[String] = List(fruits:apple, fruits:banana, fruits:berries, fruits:apricot, fruits:lemon)

Above code, appends the text fruits: to every element in the list and produces a new list.

Using ForEach

scala> listone.foreach(x=> println(x))
apple
banana
berries
apricot
lemon

foreach: Applies a function f to all elements of this list.

Filtering Scala Lists

Often we need to filter the lists based on specific conditions and only process the elements in the if it matches the filter condition. This is easily done using the filter function

scala> val listone = List("apple","banana","berries","apricot","lemon")
scala> listone.filter(_.startsWith("a"))
res5: List[String] = List(apple, apricot)

scala> listone.filter(_.startsWith("b"))
res6: List[String] = List(banana, berries)

There is also a handy find method if you want to find the first element matching a given condition. Please note that this function returns only one element , the first one matching the condition. Also the return type is an Option[T]

scala> val listone = List("apple","banana","berries","apricot","lemon")
scala> listone.find(_.startsWith("a"))
res7: Option[String] = Some(apple)

Leave a Comment