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
When you need to filter
and map
at the same time, use collect
:
list1.collect { case (c, "valid") => c } intersect list2
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With