Skip to content

Instantly share code, notes, and snippets.

@ssuravarapu
Created March 19, 2012 23:41
Show Gist options
  • Save ssuravarapu/2128505 to your computer and use it in GitHub Desktop.
Save ssuravarapu/2128505 to your computer and use it in GitHub Desktop.
Calculate number of times each element repeats in the List
scala> val l = "a" :: "b" :: "c" :: "b" :: "a" :: List()
l: List[java.lang.String] = List(a, b, c, b, a)
scala> val distinct = l.distinct
distinct: List[java.lang.String] = List(a, b, c)
scala> distinct zip (distinct map (p => l.filter(p == _).size))
res0: List[(java.lang.String, Int)] = List((a,2), (b,2), (c,1))
@JasonGiedymin
Copy link

val testText = "hello, world, hello, world one two three one two three, four five six seven eight nine ten"

val cleansedList = testText.replace(",","").split(" ")
val wordMap = cleansedList.distinct.map(word => (word, cleansedList.count(_ == word) )).toMap

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment