Scala collection operations are powerful tools for manipulating data structures. They provide a functional and concise way to transform, filter, and aggregate elements in collections.
The map
operation applies a function to each element in a collection, creating a new collection with the transformed elements.
val numbers = List(1, 2, 3, 4, 5)
val doubled = numbers.map(_ * 2)
// Result: List(2, 4, 6, 8, 10)
Use filter
to create a new collection containing only elements that satisfy a given predicate.
val numbers = List(1, 2, 3, 4, 5)
val evens = numbers.filter(_ % 2 == 0)
// Result: List(2, 4)
fold
combines elements of a collection using a binary operator, starting with an initial value.
val numbers = List(1, 2, 3, 4, 5)
val sum = numbers.fold(0)(_ + _)
// Result: 15
Similar to fold
, reduce
combines elements but uses the first element as the initial value.
val numbers = List(1, 2, 3, 4, 5)
val product = numbers.reduce(_ * _)
// Result: 120
flatMap
is a combination of map
and flatten
, useful for operations that return collections.
val words = List("Hello", "World")
val chars = words.flatMap(_.toLowerCase)
// Result: List('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
Use groupBy
to partition a collection into a map of collections according to a function.
val numbers = List(1, 2, 3, 4, 5)
val grouped = numbers.groupBy(_ % 2 == 0)
// Result: Map(false -> List(1, 3, 5), true -> List(2, 4))
To deepen your understanding of Scala collections, explore these related topics:
Mastering Scala collection operations is crucial for writing efficient and expressive code. Practice with different collection types and operations to become proficient in data manipulation with Scala.