How to transform one Scala collection to another with the map function (method) |

  1. Home
  2. map design tutorials
  3. How to transform one Scala collection to another with the map function (method) |

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.14, “How to Transform One Scala Collection to Another With the map function (method)” Like the previous recipe, you want to transform one Scala sequential collection (Seq, List, Vector, ArrayBuffer, etc.) into another by applying an algorithm to every element in the original collection. Rather than using the for/yield combination shown in the previous recipe, call the map method on your collection, passing it a function, an anonymous function, or method to transform each element. This is shown in the following examples, where each String in a List is converted to begin with a capital letter: A function that’s passed into the map method can be as complicated as necessary. An example in the Discussion shows how to use a multiline anonymous function with map. When your algorithm gets longer, rather than using an anonymous function, define the function (or method) first, and then pass it into map: When writing a method to work with map, define the method to take a single parameter that’s the same type as the collection. In this case, plusOne is defined to take a char, because a String is a collection of Char elements, so map will operate on one Char at a time. The return type of the method can be whatever you need for your algorithm. For instance, the previous example showed that a function applied to a String can return an Int. Unlike the for/yield approach shown in the previous recipe, the map method also works well when writing a chain of method calls. For instance, you can split a String into an array of strings, then trim the blank spaces from those strings: This works because split creates an Array[String], and map applies the trim method to each element in that array before returning the final array. But once you add a guard, a for/yield loop is no longer directly equivalent to just a map method call. If you attempt to use an if statement in the algorithm you pass to a map method, you’ll get a very different result: But in this situation, it helps to think of an if statement as being a filter, so the correct solution is to first filter the collection, and then call map: Source.

whatsapp button