10.13. Transforming One Collection to Another with for/yield
You want to create a new collection from an existing collection by transforming the elements with an algorithm.
and your algorithm to create the new collection. For instance, starting
with a basic collection:
val a = Array(1, 2, 3, 4, 5)a: Array[Int] = Array(1, 2, 3, 4, 5)
You can create a copy of that collection by just “yielding” each element (with no algorithm):
for (e <- a) yield eres0: Array[Int] = Array(1, 2, 3, 4, 5)
You can create a new collection where each element is twice the value of the original:
for (e <- a) yield e * 2res1: Array[Int] = Array(2, 4, 6, 8, 10)
You can determine the modulus of each element:
for (e <- a) yield e % 2res2: Array[Int] = Array(1, 0, 1, 0, 1)
This example converts a list of strings to uppercase:
val fruits = Vector("apple", "banana", "lime", "orange")fruits: Vector[String] = Vector(apple, banana, lime, orange) scala>
val ucFruits = for (e <- fruits) yield e.toUpperCaseucFruits: Vector[String] = Vector(APPLE, BANANA, LIME, ORANGE)
Your algorithm can return whatever collection is needed. This
approach converts the original collection into a sequence of
for (i <- 0 until fruits.length) yield (i, fruits(i))res0: scala.collection.immutable.IndexedSeq[(Int, String)] = Vector((0,apple), (1,banana), (2,lime), (3,orange))
This algorithm yields a sequence of
Tuple2 elements that contains each original ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.