Scala Collections

Working with Scala collections

Lists

val list = List(1, 2, 3) # immutable list
val empty = List() # empty list
list.head # first element
list.tail # all except first
list.isEmpty # check if empty
0 :: list # prepend element

List Operations

list.length # get length
list.reverse # reverse list
list.sorted # sort list
list1 ::: list2 # concatenate lists
list.mkString("", "") # join to string

Arrays

val arr = Array(1, 2, 3) # mutable array
arr(0) # access element
arr(0) = 10 # modify element
arr.length # get length

Sets

val set = Set(1, 2, 3) # immutable set
set + 4 # add element (returns new set)
set - 1 # remove element
set.contains(2) # check membership

Maps

val map = Map("a" -> 1, "b" -> 2) # immutable map
map("a") # get value
map.get("a") # returns Option
map + ("c" -> 3) # add key-value pair
map - "a" # remove key

Higher-Order Functions

list.map(_ * 2) # transform elements
list.filter(_ > 1) # filter elements
list.reduce(_ + _) # reduce to single value
list.foreach(println) # iterate
list.find(_ > 2) # find first match