Histogram inScala

scala> val hist=Array("aa","bb","aa").foldLeft(Map[String,Int]()){
| (m,c) => m + (c -> (m.getOrElse(c,0)+1))
| }

or use the updated method of mutable Map

scala> val hist=Array("aa","bb","aa").foldLeft(Map[String,Int]()){
| (m,c) => m.updated(c, m.getOrElse(c,0)+1)
| }

Print histogram with sorted keys

scala> hist.toSeq.sortBy(_._1).foreach(println)
(aa,2)
(bb,1)
This entry was posted in Scala, Spark. Bookmark the permalink.

Leave a comment