0

I have a word-frequency array like this:

[("hello", 1), ("world", 5), ("globle", 1)]

I have to reverse it such that I get frequency-to-wordCount map like this: [(1, 2), (5, 1)]

Notice that since two words ("hello" and "globe") have the frequency 1, the value of the reversed mapping is 2. However, since there is only one word with a frequency 5, so, the value of that entry is 1. How can I do this in scala?

Update:

I happened to figure this out as well:

arr.groupBy(_._2).map(x => (x._1,x._2.toList.length))
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Darth.Vader
  • 5,079
  • 7
  • 50
  • 90
  • 3
    Possible duplicate of [Scala how can I count the number of occurrences in a list](http://stackoverflow.com/questions/11448685/scala-how-can-i-count-the-number-of-occurrences-in-a-list) – Neo-coder Nov 21 '16 at 18:24
  • You don't need `.toList` since the `x._2` collection already has a `length` method. – jwvh Nov 21 '16 at 18:54

1 Answers1

4

You can first group by the count, and then just get the size of each group

val frequencies = List(("hello", 1), ("world", 5), ("globle", 1))
val reversed = frequencies.groupBy(_._2).mapValues(_.size).toList
res0: List[(Int, Int)] = List((5,1), (1,2))
Łukasz
  • 8,555
  • 2
  • 28
  • 51
  • thanks. I happened to figure out an alternate answer as well. Updating my original post with that too. thank you. – Darth.Vader Nov 21 '16 at 18:28