加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 根据可选参数值过滤列表

发布时间:2020-12-16 19:21:40 所属栏目:安全 来源:网络整理
导读:是否有更优雅的方法根据可选参数值过滤列表? def f(dates: List[Date],start: Option[Long],end: Option[Long]): List[Date] = { (start,end) match { case (Some(s),Some(e)) = dates filter (_.getTime s) filter (_.getTime e) case (Some(s),None) = da
是否有更优雅的方法根据可选参数值过滤列表?

def f(dates: List[Date],start: Option[Long],end: Option[Long]): List[Date] = {
    (start,end) match {
        case (Some(s),Some(e)) =>  dates filter (_.getTime > s) filter (_.getTime < e)
        case (Some(s),None) => dates filter (_.getTime > s)
        case (None,Some(e)) => dates filter (_.getTime < e)
        case (None,None) => dates
    }
}

有三个可选参数值,这将有9个案例等.

解决方法

一种方法如下:

def f(dates: List[Date],end: Option[Long]): List[Date] =
  dates.filter( d => start.map(d.getTime > _).getOrElse(true) )
       .filter( d => end.map(d.getTime < _).getOrElse(true) )

或者,更简洁,您可以在选项上使用forall:

def f(dates: List[Date],end: Option[Long]): List[Date] =
  dates.filter( d => start.forall(d.getTime > _) )
       .filter( d => end.forall(d.getTime < _) )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读