Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Using Filter to see if the value in one list matches the value in the same index in another list

Tags:

scala

Given 2 Lists and using the Filter method, i am required to write a function that will take these 2 lists, filter through them and then compare if the value in one index on one list matches the value in the same index on the other list

Example VVV

scala> val list1 = List(1,2,3,10)
scala> val list2 = List(3,2,1,10)
scala> val mn = matchedNumbers(list1, list2)
List(2,10)

The method is called "matchedNumbers"

Any help would be appreciated. Thanks

like image 231
Biomechanic Avatar asked Jan 27 '23 10:01

Biomechanic


1 Answers

The solution is almost the same as of @talex, only using collect:

def matchedNumbers(list1: List[Int], list2: List[Int]) = 
  list1.zip(list2).collect{case (x, y) if x == y => x}
like image 93
Nyavro Avatar answered Jan 29 '23 00:01

Nyavro