首页 > 解决方案 > 在对象列表中,如何在 Scala 的同一个列表中减去一个对象的字段与另一个对象的相同字段?

问题描述

我有以下案例类:

case class AgeDiff(serviceLocation: ServiceLocation, daysBehind: Option[Long])
case class ServiceLocation(
    environment: String,
    service: String,
    pool: String,
    region: String
)

我有一个List[AgeDiff]

此列表中只有两种可能的环境serviceLocation

QA&Prod

该列表的一个示例可能是:

val ageDiffList = List(
    AgeDiff(
      ServiceLocation("qa", "a-service", "poolC", "us-west-4"),
      Some(6)
    ),
    AgeDiff(
      ServiceLocation("prod", "a-service", "poolC", "us-west-4"),
      Some(7)
    ),AgeDiff(
      ServiceLocation("qa", "b-service", "poolC", "us-west-4"),
      Some(8)
    ),
    AgeDiff(
      ServiceLocation("prod", "b-service", "poolC", "us-west-4"),
      Some(10)
    )
)

我想返回一个新的List[AgeDiff],我daysBehind 从所有具有serviceLocationin的 AgeDiff 中减去prod具有serviceLocationin的 AgeDiffqa

例如,当列表减法发生时,它将如下所示:

val ageDiffList = List(
    AgeDiff(
      ServiceLocation("qa", "a-service", "poolC", "us-west-4"),
      Some(6)
    ),
    AgeDiff(
      ServiceLocation("prod", "a-service", "poolC", "us-west-4"),
      Some(1)

    ),AgeDiff(
      ServiceLocation("qa", "b-service", "poolC", "us-west-4"),
      Some(8)
    ),
    AgeDiff(
      ServiceLocation("prod", "b-service", "poolC", "us-west-4"),
      Some(2)
    )
)


条件是:

例如:

   AgeDiff(
      ServiceLocation("qa", "a-service", "poolC", "us-west-4"),
      Some(6)
    ),
    AgeDiff(
      ServiceLocation("prod", "a-service", "poolC", "us-west-4"),
      Some(7)
    )

不是

   AgeDiff(
      ServiceLocation("qa", "a-service", "poolC", "us-west-4"),
      Some(6)
    ),
    AgeDiff(
      ServiceLocation("prod", "b-service", "poolC", "us-west-4"),
      Some(7)
    )

例如:

   AgeDiff(
      ServiceLocation("qa", "a-service", "poolb", "us-west-3"),
      Some(6)
    ),
    AgeDiff(
      ServiceLocation("prod", "a-service", "poolC", "us-west-4"),
      Some(7)
    )

除非他们有相同的游泳池、地区和服务,或者他们落后于比赛几天,否则他们可能会崩溃。但是,服务名称必须相同才能减去。

标签: listscalaobject

解决方案


好的,规格仍然有点模糊,但我会尝试一下。

val newADList =
  ageDiffList.foldLeft((List[AgeDiff](),Map[ServiceLocation,Long]())){
    case ((acc, mp)
         ,ad@AgeDiff(sl@ServiceLocation("qa",_,_,_),less)) =>
      (ad::acc, mp+(sl.copy(environment="prod") -> less.getOrElse(0L)))
    case ((acc, mp)
         ,ad@AgeDiff(sl@ServiceLocation("prod",_,_,_),Some(x))) =>
      (ad.copy(daysBehind = Some(x - mp.getOrElse(sl,0L)))::acc, mp)
    case ((acc, mp), ad) => (ad::acc, mp)
  }._1.reverse

这假定 a"qa"daysBehind不会None被忽略,而是有效地关闭所有具有匹配值的后续元素中的减法。"prod"SeviceLocation


推荐阅读