scala,根据几个条件过滤集合

标签 scala

我有一个代码,例如:

val strs = List("hello", "andorra", "trab", "world")
def f1(s: String) = !s.startsWith("a")
def f2(s: String) = !s.endsWith("b")

val result = strs.filter(f1).filter(f2)

现在,应根据条件应用 f1 和 f2,例如:
val tmp1 = if (cond1) strs.filter(f1) else strs
val out  = if (cond2) tmp1.filter(f2) else tmp1

有没有更好的方法来做到这一点,而不使用临时变量 tmp1 ?

一种方法是根据函数列表进行过滤,例如:
val fs = List(f1 _,f2 _)
fs.foldLeft(strs)((fn, list) => list.filter(fn))

但是随后我需要根据条件构建一个函数列表(因此,我会将使用临时字符串列表变量的问题移至使用临时函数列表变量(或者我应该需要使用可变列表) )。

我看起来像这样(当然这不会编译,否则我已经有了问题的答案):
val result = 
  strs
    .if(cond1, filter(f1))
    .if(cond2, filter(f2))

最佳答案

您可以轻松使用隐式类为您提供以下语法:

  val strs = List("hello", "andorra", "trab", "world")

  def f1(s: String) = !s.startsWith("a")

  def f2(s: String) = !s.endsWith("b")

  val cond1 = true
  val cond2 = true

  implicit class FilterHelper[A](l: List[A]) {
    def ifFilter(cond: Boolean, f: A => Boolean) = {
      if (cond) l.filter(f) else l
    }
  }

  strs
    .ifFilter(cond1, f1)
    .ifFilter(cond2, f2)

res1: List[String] = List(hello, world)

我会用 if作为方法名称,但它是一个保留字。

关于scala,根据几个条件过滤集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17406454/

相关文章:

scala - 集合结构类型参数怪异

scala - 传递类型参数以用作参数 LabelledGeneric

scala - Scala中非案例类的模式匹配

java - DateTimeFormatter.format 与大陆/城市

scala - 表达式 _GEN_7 用作 FEMALE 但只能用作 MALE

scala - 无法在Phusion/baseimage上安装Scala

scala - 窗口上的 Spark 条件滞后函数

java - mod-mysql-postgresql 在启动期间尝试下载 io.vertx~lang-scala~1.0.0 模块

Scala:哈希忽略初始大小(数十亿条目的快速哈希表)

scala - 使用 Scala Slick 创建组合主键