user2841047 user2841047 - 3 months ago 20
Scala Question

Scala - reduce function

How to use reduce function in Scala? Is there a built in function like that?
I have implemented a program to find word count in scala.

object count {
def main(args: Array[String]) {
val fruits = List("apple", "apple", "orange", "apple", "mango", "orange")
val word = fruits.flatMap(_.split("\n"))
val Map = word.map(word => (word,1)).groupBy(_._1)
val reduce = Map.map(word => (word._1,word._2.foldLeft(0)((sum,c) => sum+ c._2)))
println(reduce) }}


How to replace foldleft with reduce function?

Answer

Entire example above should be implemented like this

fruits groupBy(word => word) mapValues(_.size)

or like this as replacement for fold

val reduce = Map.map(word => (word._1,word._2.size))

but if you absolutely positively must use reduce in the same exact code, it would be something like this

val reduce = Map.map(word => (word._1,word._2.map(_=>1).reduce(_+_)))
Comments