Thursday, May 9, 2013

Scala - Transform All Elements in a Scala Collection

Often times, you need to transform all of the elements in a Scala collection. This is where the map method comes in handy. With the map method, you can apply a function to all of the elements in a collection and obtain a new collection with the results. Here's an example that uses the map method to create a new list where all of the elements in the list are converted to uppercase.

val places = List("Atlanta", "Chicago", "Dallas", "New York City")
val uppercasePlaces =

This has the same effect as iterating over all of the elements and calling toUpperCase on each element individually.

Sometimes you'll have a collection of various types. For example, your collection might contain Int and String values and you want to convert all of the String values to uppercase and still keep the Int values in the resulting list. For this, we have the collect method, along with case classes. Here's an example.

val numbersAndStrings = List(1, "Atlanta", 10, "Boston", "Dallas")
val numbersAndUppercaseStrings = numbersAndStrings.collect {
   case s: String => s.toUpperCase; case i: Int => i

No comments:

Post a Comment