fleo
fleo

Reputation: 37

Filter out elements by comparing a list of strings and a map

I have two functions which get a list of Strings and a Map as parameters and return a list of Integers. As shown:

def f1(names: List[String], namemap: Map[String, List[Int]]): List[Int] = 

def f2(names: List[String], namemap: Map[String, List[Int]]): List[Int] =

To make the following explanation more understandable here is an example:

val nameslist = List("alex", "toby")

val namesmap = Map("sarah" -> List(5), "toby" -> List(6), "alex" -> List(1, 6))

println(f1(nameslist, namesmap))
//should print: List(6,1)
println(f2(nameslist, namesmap))
//should print: List(6)

The function f1 should "compare"? the Strings from the List namelist with the Strings from the Map namesmap and returns all the Integer values from namesmap where the String is found.

The function f2 should only return the Integers which are found in both Strings.

Upvotes: 0

Views: 227

Answers (1)

jwvh
jwvh

Reputation: 51271

This should help.

val nameslist = List("alex", "toby", "jo")
val namesmap =
  Map("sarah" -> List(5), "toby" -> List(6), "alex" -> List(1, 6))

nameslist.flatMap(namesmap.get)  //List[List[Int]]
         .flatten                //List[Int]
         .distinct               //duplicates removed
//res0: List[Int] = List(1, 6)

nameslist.flatMap(namesmap.get)       //List[List[Int]]
         .reduceOption(_ intersect _) //Option[List[Int]]
         .getOrElse(Nil)              //List[Int]
//res1: List[Int] = List(6)

Upvotes: 1

Related Questions