← Back to Scala Course | Chapter 6: Collections Basics | Lesson 2 of 8

List Operations (head/tail/map/filter)

List Operations (head/tail/map/filter)

.head returns a list's first element (throwing if the list is empty), and .tail returns every element after the first as a new list. .map(f) transforms every element and returns a new list of results, and .filter(p) keeps only elements matching a predicate. These are the fundamental building blocks for working with immutable lists functionally.

Warning: Calling .head or .tail on an empty list throws a NoSuchElementException/UnsupportedOperationException -- check .isEmpty or use .headOption first if unsure.

Example: List Operations (head/tail/map/filter)

markup
object Main extends App {
  val numbers = List(1, 2, 3, 4, 5)

  println(numbers.head)
  println(numbers.tail)

  val doubled = numbers.map(n => n * 2)
  val evens = numbers.filter(n => n % 2 == 0)

  println(doubled)
  println(evens)
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.