Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reverse a Map which has A Set as its value using HOF

I am trying to reverse a map that has a String as the key and a set of numbers as its value

My goal is to create a list that contains a tuple of a number and a list of strings that had the same number in the value set

I have this so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def flipMap(toFlip: Map[String, Set[Int]]): List[(Int, List[String])] = {
  toFlip.flatMap(_._2).map(x => (x, toFlip.keys.toList)).toList
}

but it is only assigning every String to every Int

val map = Map(
 "A" -> Set(1,2),
 "B" -> Set(2,3)
)

should produce:
List((1, List(A)), (2, List(A, B)), (3, List(B)))

but is producing:
List((1, List(A, B)), (2, List(A, B)), (3, List(A, B)))

>Solution :

This works to, but it’s not exactly what you might need and you may need some conversions to get the exact data type you need:

toFlip.foldLeft[Map[Int, Set[String]]](Map.empty) {
    case (acc, (key, numbersSet)) =>
      numbersSet.foldLeft[Map[Int, Set[String]]](acc) {
        (updatingMap, newNumber) =>
          updatingMap.updatedWith(newNumber) {
            case Some(existingSet) => Some(existingSet + key)
            case None => Some(Set(key))
          }
      }
  }

I used Set to avoid duplicate key insertions in the the inner List, and used Map for better look up instead of the outer List.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading