3

I am trying to create a map after getting result for each items in the list. Here is what I tried so far:

val sourceList: List[(Int, Int)] = ....
val resultMap: Map[Int, Int] = for(srcItem <- sourceList) {
  val result: Int = someFunction(srcItem._1)
  Map(srcItem._1 -> result)
}

But I am getting type mismatch error in IntelliJ and I am definitely not writing proper syntax here. I don't think I can use yield as I don't want List of Map. What is correct way to create Map using for loop. Any suggestion?

1 Answer 1

7

The simplest way is to create the map out of a list of tuples:

val resultMap = sourceList.map(item => (item._1, someFunction(item._1))).toMap

Or, in the monadic way:

val listOfTuples = for {
  (value, _) <- sourceList
} yield (value, someFunction(value))

val resultMap = listOfTuples.toMap

Alternatively, if you want to avoid the creation of listOfTuples you can make the transformation a lazy one by calling .view on sourceList and then call toMap:

val resultMap = sourceList.view
                          .map(item => (item._1, someFunction(item._1)))
                          .toMap

Finally, if you really want to avoid generating extra objects you can use a mutable Map instead and append the keys and values to it using += or .put

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.