user2841047 user2841047 - 1 year ago 288
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,1)).groupBy(_._1)
val reduce = => (word._1,word._2.foldLeft(0)((sum,c) => sum+ c._2)))
println(reduce) }}

How to replace foldleft with reduce function?

Answer Source

Entire example above should be implemented like this

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

or like this as replacement for fold

val reduce = => (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 = => (word._1,>1).reduce(_+_)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download