0

I'm just getting used to Scala and I have

case class Person(name: String, birthPlace: String, hairColor: String)

I know that there should be a good way to convert a List[Person] to

Map[Name, Map[Birthplace, Person]]

But, I can't quite figure out how to do it.

Any and all help would be appreciated.

1
  • just a general question: Why not store 2 separate maps (assuming multiple people can have the same birthplace)? Map[Name,List[Person]] and Map[Birthplace,List[Person]] and then resultPersonListA.intersect(resultPersonListB) ? The advantage imo is that you have direct access to both maps? Commented Jul 12, 2016 at 20:19

1 Answer 1

4

There could be more then one person with the same name and birthplace, so a better data type for this kind of thing would be Map[String, Map[String, Seq[Person]]. You can create it using .groupBy:

    list
      .groupBy(_.name)
      .mapValues(_.groupBy(_.birthplace))

If you want to ignore multiple occurrences, you can discard them by adding this at the end:

      .mapValues(_.mapValues(_.head))
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.