Miko
Miko

Reputation: 2633

Scala for comprehension with Map iteration

I gone through a bunch of codes and tutorials and i still don’t understand how to iterate the Map through the for comprehension.

For example : I have a Map. Key as a string (student name) and the value as student details. I wants to iterate the student Map as each key and value. How can i achieve this through for comprehension.

Here’s the code i tried but i failed to understand

for {   
  studentMap <- studRepo.getAllStudent()// returns a map
  result1 <- performSomeOper(studentMap.key) // I’m not getting an option to access the key/value
  result2 <- performSomeOper(studentMap.value)
} yield performYieldOps(result1, result2)

What i’m doing wrong here ? Do i needs to keep the studentMap outside the for comprehension? Please feed me your input.

Upvotes: 1

Views: 1628

Answers (1)

chengpohi
chengpohi

Reputation: 14217

  for {
    (key, value) <- studRepo.getAllStudent()
    res1 <- performSomeOper(key)
    res2 <- performSomeOper(value)
  } yield ...

You can map key, value from Map.

and for comprehension actual is equal to flatMap, so for the above equal to:

  m.flatMap {
    case (key, value) => ...
  }

Upvotes: 3

Related Questions