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.
In this page:
Syntax
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)
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)
}
Login to try C/C++/Java/PHP code in the editor
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
- Calling
.heador.tailon an empty list, which throws an exception; useheadOptionor checkisEmpty. - Expecting
mapto change the list, when it returns a new list and the original stays the same. - Using
filterwith a predicate that returns a non-Boolean, or forgettingn =>, such asnumbers.filter(n % 2 == 0).
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: