0

This is a very simple code that can be executed inside a Scala Worksheet also. It is a map reduce kind of approach to calculate frequency of the numbers in the list.

I am sorting the list before I am starting the groupBy and map operation. Even then the list.groupBy.map operation generates a map, which is not sorted. Neither number wise nor frequency wise

//put this code in Scala worksheet

//this list is sorted and sorted in list variable

val list = List(1,2,4,2,4,7,3,2,4).sorted

//now you can see list is sorted

list

//now applying groupBy and map operation to create frequency map    

val freqMap = list.groupBy(x => x) map{ case(k,v) => k-> v.length } 

freqMap
Tahseen
  • 1,027
  • 1
  • 12
  • 32
  • 1
    Already has an explanation and answer here: http://stackoverflow.com/questions/14434160/why-does-groupby-in-scala-change-the-ordering-of-a-lists-items Maps are not sorted by keys by default. Use: `SortedMap(list.groupBy(x => x).toSeq:_*)` to get a sorted map. – Samar Aug 23 '16 at 13:23
  • Answer is `val flist = list.groupBy(x => x).map{case(k,v)=>k->v.length}.toList.sorted` – Tahseen Aug 23 '16 at 15:39

2 Answers2

1

groupBy doesn't guarantee any order

Alexej Haak
  • 480
  • 3
  • 10
0
val list = List(1,2,4,2,4,7,3,2,4).sorted    
val freqMap = list.groupBy(x => x)

Output:

freqMap: scala.collection.immutable.Map[Int,List[Int]] = Map(1 -> List(1), 2 -> List(2, 2, 2), 7 -> List(7), 3 -> List(3), 4 -> List(4, 4, 4))

groupBy takes the list and groups the elements. It builds a Map in which the

  • key is a unique value of the list
  • value is a List of all occurrence in the list.

Here is the official method definition from the Scala docs:

def groupBy [K] (f: (A) ⇒ K): Map[K, Traversable[A]] 

If you want to order the grouped result you can do it with ListMap:

scala> val freqMap = list.groupBy(x => x)
freqMap: scala.collection.immutable.Map[Int,List[Int]] = Map(1 -> List(1), 2 -> List(2, 2, 2), 7 -> List(7), 3 -> List(3), 4 -> List(4, 4, 4))

scala> import scala.collection.immutable.ListMap
import scala.collection.immutable.ListMap

scala> ListMap(freqMap.toSeq.sortBy(_._1):_*)
res0: scala.collection.immutable.ListMap[Int,List[Int]] = Map(1 -> List(1), 2 -> List(2, 2, 2), 3 -> List(3), 4 -> List(4, 4, 4), 7 -> List(7))
Avi Chalbani
  • 842
  • 7
  • 11
  • I know what groupBy does. What am saying is that when I sorted the list, then why is groupBy not grouping the elements in the order of the list ? – Tahseen Aug 23 '16 at 14:04
  • The return Map is not ordered. Scala map is a collection of key/value pairs and keys are unique in the Map. Maps are also called Hash tables, hence the keys are not in an alphanumeric order. If you want to apply an order you can do it on the return map. i just have extended my post, – Avi Chalbani Aug 28 '16 at 12:45