Search code examples
scalamapreducemap-function

scala - count every line in which a word occurs


I want to find create a Map that has a word as a key and a List of integers as a value. The Integers in the list should represent the line numbers as indices. Like so:

Map("test" -> List(0, 2), "test2"->List(1),"foo" -> List(0, 3), "bar" -> List(2))

This would mean that the word test occurred in line 0&2, foo in line 0&3 and bar only in line 2.
I already managed to create a list of all words that occur in one line of text and read them to a list e.g.

val wordsWithLine= List((0,"test"), (0,"foo"), (1,"test2"), (2,"test"), (2,"bar"), (0,"test"), (3,"foo"))

Now I'm stuck and have no Idea how I can create this map. I know that the function definition has to look like this, but I have no idea how to implement it:

def createIndexMap(listwithIndices: List[(Int, String)]): Map[String, List[Int]] = {???}

My idea was to use groupMapReduce() ? But I can't wrap my head around how this works.

I'm very new to Scala and functional programming in general so any tips would be highly appreciated


Solution

  • You only need groupMap

    def createIndexMap(listwithIndices: List[(Int, String)]): Map[String, List[Int]] =
      listwithIndices.groupMap(_._2)(_._1)