通过与另一个列表进行比较来更新对象列表

时间:2017-03-29 14:24:22

标签: list groovy

我有两个不同的同一对象列表,一个是样本数据,一个是真实数据。实际数据中的几个字段搞砸了,我需要通过从样本数据中获取这些值来更新实际数据列表的几个字段。

两个列表都是相同的对象,都有相同的唯一键。

List<pojo> real = [(code:60,active:Y,account:check),(code:61,active:Y,account:check),(code:62,active:Y,account:check)];

List<pojo> sample = [(code:60,active:Y,account:saving),(code:61,active:Y,account:check),(code:62,active:Y,account:saving)]

我在每个列表中有大约60个对象,在上面我需要更新代码为60和62的真实位置 - 从检查到保存的帐户。

我正在使用java 1.8&amp; groovy

感谢

2 个答案:

答案 0 :(得分:1)

这是你需要的吗?

class Pojo {
    def code
    def active
    def account

    String toString() {
        account
   }
}

List<Pojo> real = [new Pojo(code: 60, active: 'Y', account: 'check'), new Pojo(code: 61, active: 'Y', account: 'check'), new Pojo(code: 62, active: 'Y', account: 'check')]

List<Pojo> sample = [new Pojo(code: 60, active: 'Y', account: 'saving'), new Pojo(code: 61, active: 'Y', account: 'check'), new Pojo(code: 62, active: 'Y', account: 'saving')]

real.each { r ->
    def acc = sample.find{it.code == r.code}?.account

    if (acc != null) {
        r.account = acc
    }
}

println real // prints [saving, check, saving]

上面的示例在每个pojo中实际迭代,并在示例列表中搜索相应的对象(具有相同代码)。如果找到相应的对象,则覆盖真实列表的对象中的帐户值,否则它将保持原样。

答案 1 :(得分:0)

以下是在与OP请求的real数据进行比较后更新sample数据的脚本。

请注意,输入无效,因此通过将列表中的值更改为map来使其有效。即,

(code:60,active:'Y',account:'check')改为 到[code:60,active:'Y',account:'check']

def realData = [[code:60,active:'Y',account:'check'],[code:61,active:'Y',account:'check'],[code:62,active:'Y',account:'check']]  
def sampleData = [[code:60,active:'Y',account:'saving'],[code:61,active:'Y',account:'check'],[code:62,active:'Y',account:'saving']]
realData.collect{rd -> sampleData.find{ it.code == rd.code && (it.account == rd.account ?: (rd.account = it.account))}}
println realData

<强>输出:

[[code:60, active:Y, account:saving], [code:61, active:Y, account:check], [code:62, active:Y, account:saving]]

您可以快速在线试用 Demo