# 10.13. Transforming One Collection to Another with for/yield

## Problem

You want to create a new collection from an existing collection by transforming the elements with an algorithm.

## Solution

Use the `for`/`yield` construct and your algorithm to create the new collection. For instance, starting with a basic collection:

```scala> `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):

```scala> `for (e <- a) yield e`
res0: Array[Int] = Array(1, 2, 3, 4, 5)```

You can create a new collection where each element is twice the value of the original:

```scala> `for (e <- a) yield e * 2`
res1: Array[Int] = Array(2, 4, 6, 8, 10)```

You can determine the modulus of each element:

```scala> `for (e <- a) yield e % 2`
res2: Array[Int] = Array(1, 0, 1, 0, 1)```

This example converts a list of strings to uppercase:

```scala> `val fruits = Vector("apple", "banana", "lime", "orange")`
fruits: Vector[String] = Vector(apple, banana, lime, orange)

scala> `val ucFruits = for (e <- fruits) yield e.toUpperCase`
ucFruits: 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 `Tuple2` elements:

```scala> `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.