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

List Operations (head/tail/map/filter)

List operations are quick tools for lists: head gives the first item, tail gives the rest, map changes every item, and filter keeps only the ones you want. It is like a factory line that processes each toy.
Syntax
scala
list.head
list.tail
list.map(x => expression)
list.filter(x => condition)

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling .head or .tail on an empty list, which throws an exception; use headOption or check isEmpty.
  2. Expecting map to change the list, when it returns a new list and the original stays the same.
  3. Using filter with a predicate that returns a non-Boolean, or forgetting n =>, such as numbers.filter(n % 2 == 0).
🔒

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.