Search code examples
scalahashmapcombinationspairwise

How to get the possible pair combinaisons of values of a hashmap Scala


I have a hashmap as follows :

val hm : HashMap[Int, List[String]] =
  HashMap(
    1 -> List("Eat", "Drink","Sleep", "work"),
    2 -> List("Eat", "Sleep","Dance"),
    3 -> List("Write", "Print","Dance")
  )

I want to retrieve the possible pairs of this hashmap's values and return each pair separately in a list I'm using the combinaisons function as

hm.mapValues(_.combinations(2).toList)

The result is :

 Map(1-> List(List(Eat, Drink), List(Eat, Sleep), List(Eat, work), List(Drink, Sleep), List(Drink, work), List(Sleep, work)), 2-> List(List(Eat, Sleep), List(Eat, Dance), List(Sleep, Dance)), 3 -> List(List(Write, Print), List(Write, Dance), List(Print, Dance)))

yet the expected result should be three lists

List(List("Eat", "Drink","Sleep", "work"),List("Eat", "Sleep","Dance"))
List( List("Eat", "Drink","Sleep", "work"),List("Write", "Print","Dance"))
List(List("Eat", "Sleep","Dance"), List("Write", "Print","Dance"))

What am I missing


Solution

  • use only values of your map:

    hm.values.toList.combinations(2).toList
    

    https://scalafiddle.io/sf/ZGbHC4c/0