Reputation: 4151
I have a Scala sequence which is of format ("Apple-fruit", "Banana-fruittoo", "Chocolate-notafruit")
and I have another Scala list of format ("Apple", "Banana")
I want to filter my first sequence based on second list so that my final output is ("Apple-fruit", "Banana-fruittoo")
. Could anyone help me with this filter function?
Upvotes: 3
Views: 9067
Reputation: 61666
Seq("Apple-fruit", "Banana-fruittoo", "Chocolate-notafruit")
.filter(x => Seq("Apple", "Banana").exists(y => x.contains(y)))
// Seq("Apple-fruit", "Banana-fruittoo")
For each item (x) of the seq to filter, we check if at least one element (y) of the filtering seq exists such as x contains y.
Upvotes: 6
Reputation: 1099
Try this:
x.filter(x=>y.contains(x.split("-")(0)))
for
val x = List("Apple-fruit", "Banana-fruittoo", "Chocolate-notafruit")
val y = List("Apple", "Banana")
scala> x.filter(x=>y.contains(x.split("-")(0)))
res130: List[String] = List(Apple-fruit, Banana-fruittoo)
scala>
Upvotes: 0