user461112
user461112

Reputation: 4151

Filtering a scala string sequence based on a list of strings

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

Answers (2)

Xavier Guihot
Xavier Guihot

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

RAGHHURAAMM
RAGHHURAAMM

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")

In Scala REPL:

scala> x.filter(x=>y.contains(x.split("-")(0)))
res130: List[String] = List(Apple-fruit, Banana-fruittoo)

scala>

Upvotes: 0

Related Questions