Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get common element from 2 given lists

So i have this 2 collections:

import collection.mutable.ListBuffer

val list1 = ListBuffer[(String, String)]()
list1 += (("Italy", "valid"))
list1 += (("Germany", "not valid"))
list1 += (("USA", "not valid"))
list1 += (("Romania", "valid"))

val list2 = ListBuffer[String]()
list2 += "Germany"
list2 += "USA"
list2 += "Romania"
list2 += "Italy"
list2 += "France"
list2 += "Croatia"

I want to get new list that contain common countries with specific condition for example valid so the result will be new list:

Italy, Romania
like image 870
david hol Avatar asked Feb 06 '23 14:02

david hol


2 Answers

When you need to filter and map at the same time, use collect:

list1.collect { case (c, "valid") => c } intersect list2
like image 166
dhg Avatar answered Feb 15 '23 04:02

dhg


Using a for comprehension as follows,

for ((a,"valid") <- list1 if list2.contains(a)) yield a

This comprehension desugars into a flatMap and a lazy filter. We pattern match (extract) those tuples whose second item matches "valid" and check whether the validated country belongs to the second list.

like image 29
elm Avatar answered Feb 15 '23 05:02

elm