val places = List("Atlanta", "Chicago", "Dallas", "New York City") val uppercasePlaces = places.map(_.toUpperCase)
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