Created
October 28, 2014 20:04
-
-
Save emres/91508521303238b14d42 to your computer and use it in GitHub Desktop.
Alternative methods for creating a new structure based on an existing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given the following: | |
*/ | |
val myArray = Array(("the", (1, 2)), ("word", (3, 4)), ("count", (5, 6))) | |
/** | |
* How can we create a new Array such as | |
* | |
* Array(("the", 3), ("word", 7), ("count", 11)) | |
* | |
*/ | |
/** | |
* Let's see four alternative methods: | |
* | |
*/ | |
// 1 | |
for (x <- myArray) yield (x._1, x._2._1 + x._2._2) | |
// 2 | |
for { | |
x <- myArray | |
word = x._1 | |
counts = x._2 | |
} yield (word, counts._1 + counts._2) | |
// 3 | |
myArray.map(x => (x._1, x._2._1 + x._2._2)) | |
// 4 | |
myArray.collect{case (word, tuple) => (word, tuple._1 + tuple._2)} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment