Scala过滤2个条件以从列表中删除字符串

时间:2016-08-10 14:02:42

标签: scala

这感觉它应该非常简单但经过几次变化我无法返回正确的结果。

我有一个我想要过滤的字符串列表和一组我用作黑名单的字符串。如果我列表中的任何字符串都在黑名单中,那么我想忽略它们,只返回不存在的字符串。除此之外我还有另外一个需要检查的案例,所以我需要确保它不在黑名单中,也不是条件二。

strings.filter(f => !f.endsWith("-else")) 

我正在尝试做类似的事情:

{{1}}

只留下“某事”和“something.else”,但我似乎无法单独回归“某事”。

2 个答案:

答案 0 :(得分:2)

strings.filter(
  f => !f.endsWith("-else") && !blacklist.exists(suffix => f.endsWith(suffix))
)

或更短(但相同)的版本:

strings.filter(f => !f.endsWith("-else") && !blacklist.exists(f.endsWith))

答案 1 :(得分:1)

我知道如果元素以黑名单中的内容结尾,则要删除该元素。 你可以试试像

这样的东西
strings.filter {x => (blacklist map {word => !(x endsWith word)}  reduce( (a,b) => a && b ) ) }

有另一个条件,例如x.length >= 2

strings.filter {x => (blacklist map {word => !(x endsWith word)}  reduce( (a,b) => a && b ) ) && x.length >= 2}