Ashwin Praveen Ashwin Praveen - 23 days ago 5
Scala Question

Finding common strings from map type and array Scala without loops

I am trying to find the common strings in a map and an array to output the respective values(from map, values here is Map[key -> value]) in Scala, I'm trying to not use any loops. Example:

Input:

Array("Ash","Garcia","Mac") Map("Ash" -> 5, "Mac" -> 4, "Lucas" -> 3)


Output:

Array(5,4)


The output is an array with 5 and 4 because Ash and Mac are common in both the data structures

Answer Source

Use .filter to find the matching entries only, then get the value of your filtered map.

Given

scala> val names = Array("Ash","Garcia","Mac")
names: Array[String] = Array(Ash, Garcia, Mac)

scala> val nameToNumber = Map("Ash" -> 5, "Mac" -> 4, "Lucas" -> 3)
nameToNumber: scala.collection.immutable.Map[String,Int] = Map(Ash -> 5, Mac -> 4, Lucas -> 3)

.filter.map

scala> nameToNumber.filter(x => names.contains(x._1)).map(_._2)
res3: scala.collection.immutable.Iterable[Int] = List(5, 4)

Alternatively, you can use collect,

scala> nameToNumber.collect{case kv if names.contains(kv._1) => kv._2}
res6: scala.collection.immutable.Iterable[Int] = List(5, 4)

Your complexity here is O(n2)