Nancy
Nancy

Reputation: 279

Retrieving values from a map for a filtered set of keys

I'm new to Scala programming and am looking for a way to retrieve a list of values from a map for a filtered set of keys in another map.

Ex- filter =[k1,k2,k3] inputMap=[k1->1, k1->2, k2->6, k2->7, k2->9, k3->5, k10->66, k4->45]

outputMap = [k1->(1,2),k2->(6,7,9),k3->(5)]

Thanks in advance! -Nancy

Upvotes: 1

Views: 99

Answers (1)

Nyavro
Nyavro

Reputation: 8866

Your example of 'inputMap' looks more like list of key-value pairs, because map cannot contain duplicate keys. So:

val list = List("k1"->1, "k1"->2, "k2"->6, "k2"->7, "k2"->9, "k3"->5, "k10"->66, "k4"->45)
val f = Set("k1", "k2", "k3")  //filter

First filter only required keys:

scala>val filtered = list.filter {case (k,v)=>f(k)}
filtered: List[(String, Int)] = List((k1,1), (k1,2), (k2,6), (k2,7), (k2,9), (k3,5))

Next grouping by key:

scala>val grouped = filtered.groupBy(_._1)
grouped: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(k2 -> List((k2,6), (k2,7), (k2,9)), k1 -> List((k1,1), (k1,2)), k3 -> List((k3,5)))

Now convert to desired format:

val outputMap = grouped.map {case (k,v)=>k->v.map{case (ki,vi) => vi}}
outputMap: scala.collection.immutable.Map[String,List[Int]] = Map(k2 -> List(6, 7, 9), k1 -> List(1, 2), k3 -> List(5))

Upvotes: 2

Related Questions