floppalover
floppalover

Reputation: 1

How to covert multiple strings in a list to be keys in a map

I am trying to write a function that would return a map in which every word is a key and the values are pages at which the word shows up. Currently, I am stuck at the point where I have data of the following type: List(List(words),page). Is there any sensible way to reformat this data if so, please explain as I have no idea how to even begin?

object G {

  def main(args: Array[String]): Unit = {
    stwórzIndeks()
  }
    def stwórzIndeks(): Unit= {
        val linie = io.Source
        .fromResource("tekst.txt")
        .getLines
        .toList
        val zippedLinie: List[(String,Int)]=linie.zipWithIndex

        val splitt=zippedLinie.foldLeft(List.empty[(List[String],Int)])((acc,curr)=>{
            curr match {
              case (arr,int) => {
                val toAdd=(arr.split("\\s+").toList,zippedLinie.length-int)
                toAdd+:acc
              }
            }
        })
    }
}

Upvotes: 0

Views: 45

Answers (1)

You can replace that foldLet with a flatMap with an inner map to get a big List of (word, page).

val wordsAndPage = zippedLinie.flatMap {
  case (line, idx) =>
    lome.split("\\s+").toList.map(word => word -> idx + 1)
}

After that you can check for one of the grouping methods in the scaladoc.

Upvotes: 2

Related Questions