Last active
April 27, 2017 15:29
-
-
Save talonx/a36a1d34de77a46230f413b7337b5a3d to your computer and use it in GitHub Desktop.
This file contains 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
import scala.collection.mutable.Map | |
object reduce { | |
def reduceByKey(func: (Int, Int) => Int, pairs: List[(String, Int)]): Map[String, Int] = { | |
val ret = Map[String, Int]() | |
for (tup <- pairs) { | |
val k = tup._1 | |
val v = tup._2 | |
val nv = ret.getOrElse(k, 0) | |
ret(k) = func(nv, v) | |
} | |
ret | |
} | |
def main(args :Array[String]) { | |
val l = List("the quick brown fox", "jumps over the lazy dog", "how mumbo jumbo", "took over the world", "the world is flat") | |
val fm = l.flatMap(line => line.split(" ")).map(w => (w, 1)) | |
val fin = reduceByKey((a, b) => (a + b), fm) | |
println(fin) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment