我有一个格式为("Apple-fruit", "Banana-fruittoo", "Chocolate-notafruit")
的Scala序列,我有另一个格式为("Apple", "Banana")
的Scala列表
我想根据第二个列表过滤我的第一个序列,以便我的最终输出为("Apple-fruit", "Banana-fruittoo")
。任何人都可以帮我解决这个过滤功能吗?
答案 0 :(得分:3)
Seq("Apple-fruit", "Banana-fruittoo", "Chocolate-notafruit").filter(
x => Seq("Apple", "Banana").exists(y => x.contains(y))
)
val seqToFilter = Seq("Apple-fruit", "Banana-fruittoo", "Chocolate-notafruit")
val filteringSeq = Seq("Apple", "Banana")
seqToFilter.filter(x => filteringSeq.exists(y => x.contains(y)))
对于要过滤的seq的每个项目(x),我们检查是否存在过滤seq的至少一个元素(y),例如x包含y。
答案 1 :(得分:0)
尝试一下:
x.filter(x=>y.contains(x.split("-")(0)))
为
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>