212
212

Reputation: 975

Convert a Map of Tuple into a Map of Sets

In my dao I receive a tuple[String,String] of which _1 is non-unique and _2 is unique. I groupBy based on _1 to get this -

val someCache : Map[String, List[(String, String)]]

This is obviously wasteful since _1 is being repeated for all values of the Map. Since _2 is unique, what I want is something like -

val someCache : Map[String, Set[String]]

i.e. group by _1 and use as key and use the paired _2s as value of type Set[String]

Upvotes: 0

Views: 147

Answers (2)

john sullivan
john sullivan

Reputation: 1978

def foo(ts: Seq[(String, String)]): Map[String, Set[String]] = {
  ts.foldLeft(Map[String, Set[String]]()) { (agg, t) =>
    agg + (t._1 -> (agg.getOrElse(t._1, Set()) + t._2))
  }
}


scala> foo(List(("1","2"),("1","3"),("2","3")))
res4: Map[String,Set[String]] = Map(1 -> Set(2, 3), 2 -> Set(3))

Upvotes: 1

senia
senia

Reputation: 38045

Straightforward solution is to map over all elements and convert each list to set:

someCache.map{ case (a, l) => a -> l.map{ _._2 }.toSet }

You could also use mapValues but you should note that it creates a lazy collection and performs transformation on every access to value.

Upvotes: 1

Related Questions