1

I have two lists in Scala:

val workersList = Worker1 :: Worker2 :: Worker3 :: Worker4 :: Nil // type List[Worker]
val workStationsList = WS1 :: WS2 :: WS3 :: WS4 :: Nil // type List[WorkStation]

A worker object has a parameter worksIn : List[WorkStation]

Knowing that Worker1 works in WS1 and WS2, Worker2 works in WS1 and WS2, Worker3 works in WS3 and WS4 and Worker4 works in WS3 and WS4 I want to get a HashMap[Worker, List[WorkStation]] that states exactly that.

It's result should be something like this:

Worker1 -> List(WS1 :: WS2 :: Nil)
Worker2 -> List(WS1 :: WS2 :: Nil)
Worker3 -> List(WS3 :: WS4 :: Nil)
Worker4 -> List(WS3 :: WS4 :: Nil)

I tried to do this, but it doesn't work:

val list = workersList.flatMap(w => workStationsList.map(ws => if(w.worksIn.contains(w)) w -> ws)).toMap[Worker, List[WorkStation]]

Does anyone know how can I do this?

J Costa
  • 23
  • 1
  • 3
  • 2
    Possible duplicate of [In Scala, is there a way to take convert two lists into a Map?](https://stackoverflow.com/questions/2189784/in-scala-is-there-a-way-to-take-convert-two-lists-into-a-map) – Sean Patrick Floyd Jun 09 '17 at 15:49
  • The real problem is not how to convert the two lists into a HashMap. It's how I can get the result that I want. That answer doesn't help me in my specific problem. – J Costa Jun 09 '17 at 15:52
  • Not sure what you need the second list for, you can simply do `workersList.map(w => (w, w.worksIn)).toMap` – Tzach Zohar Jun 09 '17 at 15:52

1 Answers1

1
val list = workersList.map(w => (w -> w.worksIn)).toMap // type Map[Worker, List[WorkStation]]

workStationList seems superfluous.

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54