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?

3
  • 2
    Possible duplicate of In Scala, is there a way to take convert two lists into a Map? Commented Jun 9, 2017 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. Commented Jun 9, 2017 at 15:52
  • Not sure what you need the second list for, you can simply do workersList.map(w => (w, w.worksIn)).toMap Commented Jun 9, 2017 at 15:52

1 Answer 1

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

workStationList seems superfluous.

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.