2017-03-29 25 views
-4

我确实有两个不同的同一对象列表,一个是样本数据,一个是实际数据。实际数据中的几个字段会混淆,我需要通过从样本数据中获取这些值来更新实际数据列表的几个字段。通过与另一个列表比较来更新对象列表

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

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 &常规

感谢

+1

并试图impleme时nt那功能性你特别遇到了什么问题? –

回答

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并且搜索在样品列表中的相应对象(即具有相同的码)。如果找到相应的对象,则实际列表的对象中的帐户值将被覆盖,否则它将保持原样。

0

以下是根据OP要求与sample数据比较后更新real数据的脚本。

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

(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

相关问题