list - 在对象列表中,如何在 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
从所有具有serviceLocation
in的 AgeDiff 中减去prod
具有serviceLocation
in的 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)
)
)
条件是:
- 我想对相同的 AgeDiffs 做减法
pool
,region
,service
。
例如:
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)
)
除非他们有相同的游泳池、地区和服务,或者他们落后于比赛几天,否则他们可能会崩溃。但是,服务名称必须相同才能减去。
- If
daysBehind
isNone
Then 不要比较并保持原样
解决方案
好的,规格仍然有点模糊,但我会尝试一下。
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
推荐阅读
- android - 如何使用 Retrofit 和 Gson 将字符串解析为 Android.Uri
- angular - 带有 Angular 7 的 Hammerjs 找不到 Hammer
- matlab - 如何在 matlab 中绘制一个带有第三个高度变量的 hist3?
- excel - 执行 SAP RFC 的 VBA 程序在 Excel 2016 on-prem 中有效,但在 Office 365 中无效(运行时错误 20080008...Bad Variant Type)
- prometheus - Prometheus 中类似 StatsD 的计数器行为
- c# - 为每个测试执行 XUnit 自定义数据属性
- asynchronous - Flutter 异步编程
- perl - 查找输入值大于或等于键的最近键匹配且未排序的记录
- mongodb - MongoDB:过滤 _id == obj._id 而不在插入时将 obj._id 设置为 null
- tensorflow - 将数据输入到 Tensorflow 2.0 中的已部署模型中